﻿/*
 * Rappelz: Endless Odyssey - The first free open source Rappelz server emulator
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Rappelz.GameServer.Network.AuthClient;
using Rappelz.GameServer.Database;
using Rappelz.GameServer.Scripting;

namespace Rappelz.GameServer.Network.GameClient
{
    public class GameClientNetwork : INetworkHandler
    {
        /// <summary>
        /// List of connected servers
        /// </summary>
        private static List<TCPConnection> m_clients = new List<TCPConnection>();

        private static Dictionary<string, TCPConnection> hsAuthAccount = new Dictionary<string, TCPConnection>();

        private TCPListener m_Acceptor;

        private int m_ConnectionCount = 0;
        private int m_DisconnectCount = 0;
        private int m_nRecvMessageCount = 0;
        private int m_nRecvMessageByte = 0;

        /// <summary>
        /// The instance!
        /// </summary>
        protected static GameClientNetwork m_instance;

        /// <summary>
        /// Returns the instance
        /// </summary>
        public static GameClientNetwork Instance
        {
            get { return m_instance; }
        }

        /// <summary>
        /// Returns the list of connected servers
        /// </summary>
        public static List<TCPConnection> Clients
        {
            get { return m_clients; }
        }

        /// <summary>
        /// Creates our GameServerNetwork instance
        /// </summary>
        public static void CreateInstance(TCPManager iocp)
        {
            if (m_instance == null)
                m_instance = new GameClientNetwork(iocp);
        }

        /// <summary>
        /// Constructs an GameServerNetwork object
        /// </summary>
        protected GameClientNetwork(TCPManager iocp)
        {
            m_Acceptor = new TCPListener(iocp, this, Config.srvGameClients);
            m_Acceptor.Start();
            //formLoginServer.Instance.UpdateClientStatus("Listening");

        }

        public void onConnect(int nID, TCPConnection socket)
        {
            Interlocked.Increment(ref m_ConnectionCount);
        }

        public void onDisconnect(int nID, TCPConnection socket)
        {
            Interlocked.Increment(ref m_DisconnectCount);
        }

        public PacketIn ProcessPacket(TCPConnection socket, byte[] buf, int start, int size)
        {
            PacketIn _packet = null;
            try
            {
                Player player = socket.Tag.player;

                ushort _id = Marshal.ConvertToUInt16(buf, start + 4);
                switch (_id)
                {
                    case (ushort)ClientInPackets.Login:
                        _packet = new LoginPacketCS(buf, start, size);
                        onLogin(socket, (LoginPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.TimeSync:
                        _packet = new TimeSyncPacketCS(buf, start, size);
                        onTimeSync(socket, (TimeSyncPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.MoveRequest:
                        _packet = new MoveRequestPacketCS(buf, start, size);
                        onMoveRequest(socket, (MoveRequestPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.RegionUpdate:
                        _packet = new RegionUpdatePacketCS(buf, start, size);
                        onRegionUpdate(socket, (RegionUpdatePacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Query:
                        _packet = new QueryPacketCS(buf, start, size);
                        onQuery(socket, (QueryPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.ChatRequest:
                        _packet = new ChatRequestPacketCS(buf, start, size);
                        onChatRequest(socket, (ChatRequestPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.ReturnLobby:
                        _packet = new ReturnLobbyPacketCS(buf, start, size);
                        onReturnLobby(socket);
                        break;

                    case (ushort)ClientInPackets.RequestLogoutTimer:
                    case (ushort)ClientInPackets.RequestLogoutTimer2:
                        _packet = new PacketIn(buf, start, size);
                        onRequestLogoutTimer(socket, _id);
                        break;

                    case (ushort)ClientInPackets.Logout:
                        _packet = new LogoutPacketCS(buf, start, size);
                        onLogout(socket, (LogoutPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Version:
                    case (ushort)ClientInPackets.Version2:
                        _packet = new VersionPacketCS(buf, start, size);
                        onVersion(socket, (VersionPacketCS)_packet);
                        break;

                    /*
                            HackShieldMsg = 54,
                            GameGuardAuthAnswer = 56,
                            CheckIllegalUser = 57,
                            XTrapCheck = 59,
                            Ping1 = 60,
                     */
                    case (ushort)ClientInPackets.AttackRequest:
                        _packet = new AttackRequestPacketCS(buf, start, size);
                        onAttackRequest(socket, (AttackRequestPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.CancelAction:
                        _packet = new CancelActionPacketCS(buf, start, size);
                        onCancelAction(socket, (CancelActionPacketCS)_packet);
                        break;

                     /* 

                            CancelAction = 150,

                     */
                    case (ushort)ClientInPackets.PutonItem:
                        _packet = new PutonItemPacketCS(buf, start, size);
                        onPutonItem(socket, (PutonItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.PutoffItem:
                        _packet = new PutoffItemPacketCS(buf, start, size);
                        onPutoffItem(socket, (PutoffItemPacketCS)_packet);
                        break;
                    /*

                            DropItem = 203,
                     */
                    case (ushort)ClientInPackets.TakeItem:
                        _packet = new TakeItemPacketCS(buf, start, size);
                        onTakeItem(socket, (TakeItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.EraseItem:
                        _packet = new EraseItemPacketCS(buf, start, size);
                        onEraseItem(socket, (EraseItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Storage:
                        _packet = new StoragePacketCS(buf, start, size);
                        onStorage(socket, (StoragePacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.PutonCard:
                        _packet = new PutonCardPacketCS(buf, start, size);
                        onPutOnCard(socket, (PutonCardPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.PutoffCard:
                        _packet = new PutoffCardPacketCS(buf, start, size);
                        onPutOffCard(socket, (PutoffCardPacketCS)_packet);
                        break;

                    /* 
                       ItemPositionChange = 218,

                     */
                    case (ushort)ClientInPackets.ArrangeItem:
                        _packet = new ArrangeItemPacketCS(buf, start, size);
                        onArrangeItem(socket, (ArrangeItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.BuyItem:
                        _packet = new BuyItemPacketCS(buf, start, size);
                        onBuyItem(socket, (BuyItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.SellItem:
                        _packet = new SellItemPacketCS(buf, start, size);
                        onSellItem(socket, (SellItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.UseItem:
                        _packet = new UseItemPacketCS(buf, start, size);
                        onUseItem(socket, (UseItemPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Mix:
                        _packet = new MixPacketCS(buf, start, size);
                        onMix(socket, (MixPacketCS)_packet);
                        break;
                    /* 
                             = 256,
                            DonateItem = 258,
                            DonateReward = 259,
                     */ 
                      
                    case (ushort)ClientInPackets.SoulStoneCraft:
                        _packet = new SoulStoneCraftPacketCS(buf, start, size);
                        onSoulStoneCraft(socket, (SoulStoneCraftPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.RepairSoulStone:
                        _packet = new RepairSoulStonePacketCS(buf, start, size);
                        onRepairSoulStone(socket, (RepairSoulStonePacketCS)_packet);
                        break;
                    /* 
                            OnTrade = 280, // ??
                            PutonItemSet = 281,
                            BindSkillCard = 284,
                            UnBindSkillCard = 285,
                          */
                    case (ushort)ClientInPackets.EquipSummon:
                        _packet = new EquipSummonPacketCS(buf, start, size);
                        onEquipSummon(socket, (EquipSummonPacketCS)_packet);
                        break;

                        /*
                            EquipSummon = 303,
                            ChangeSummonName = 323,
                          */
                    case (ushort)ClientInPackets.GetSummonSetupInfo:
                        _packet = new GetSummonSetupInfoPacketCS(buf, start, size);
                        onGetSummonSetupInfo(socket, (GetSummonSetupInfoPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.SetPetName:
                        _packet = new SetPetNamePacketCS(buf, start, size);
                        onSetPetName(socket, (SetPetNamePacketCS)_packet);
                        break;


                    case (ushort)ClientInPackets.Skill:
                        _packet = new SkillPacketCS(buf, start, size);
                        onSkill(socket, (SkillPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.LearnSkill:
                        _packet = new LearnSkillPacketCS(buf, start, size);
                        onLearnSkill(socket, (LearnSkillPacketCS)_packet);
                        break;

/*
                            RequestRemoveState = 408,
                      */


                    case (ushort)ClientInPackets.JobLevelUp:
                        _packet = new JobLevelUpPacketCS(buf, start, size);
                        onJobLevelUp(socket, (JobLevelUpPacketCS)_packet);
                        break;


                    case (ushort)ClientInPackets.Update:
                        _packet = new UpdatePacketCS(buf, start, size);
                        onUpdate(socket, (UpdatePacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.SetProperty:
                        _packet = new SetPropertyPacketCS(buf, start, size);
                        onSetProperty(socket, (SetPropertyPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Targeting:
                        _packet = new TargetingPacketCS(buf, start, size);
                        onTargeting(socket, (TargetingPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Resurrection:
                        _packet = new ResurrectionPacketCS(buf, start, size);
                        onResurrection(socket, (ResurrectionPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.GetRegionInfo:
                        _packet = new GetRegionInfoPacketCS(buf, start, size);
                        onGetRegionInfo(socket, (GetRegionInfoPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.DropQuest:
                        _packet = new DropQuestPacketCS(buf, start, size);
                        onDropQuest(socket, (DropQuestPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.GetQuestDetails:
                        _packet = new GetQuestDetailsPacketCS(buf, start, size);
                        onGetQuestDetails(socket, (GetQuestDetailsPacketCS)_packet);
                        break;

                     /* 
                            StartBooth = 700,
                            StopBooth = 701,
                            WatchBooth = 702,
                            StopWatchBooth = 704,
                            BuyFromBooth = 705,
                            SellToBooth = 706,
                            GetBoothsName = 707,
                            CheckBoothStartable = 711,
                            TurnOnPkMode = 800,
                            TurnOffPkMode = 801,
                      */
                    case (ushort)ClientInPackets.ChangeLocation:
                        _packet = new ChangeLocationPacketCS(buf, start, size);
                        onChangeLocation(socket, (ChangeLocationPacketCS)_packet);
                        break;

                    /*

                            GetWeatherInfo = 903,
                       */
                    case (ushort)ClientInPackets.GameTime:
                        _packet = new PacketIn(buf, start, size);
                        Messages.SendGameTime(player);
                        break;

                    case (ushort)ClientInPackets.Emotion:
                        _packet = new EmotionPacketCS(buf, start, size);
                        onEmotion(socket, (EmotionPacketCS) _packet);
                        break;
                    /*

                            AuctionSearch = 1300,
                            AuctionSellingList = 1302,
                            AuctionBiddedList = 1304,
                            AuctionBid = 1306,
                            AuctionInstantPurchase = 1308,
                            AuctionRegister = 1309,
                            AuctionCancel = 1310,
                            ItemKeepingList = 1350,
                            ItemKeepingTake = 1352,
                     */
                    case (ushort)ClientInPackets.CharacterList:
                        _packet = new CharacterListPacketCS(buf, start, size);
                        onCharacterList(socket, (CharacterListPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.CreateCharacter:
                        _packet = new CreateCharacterPacketCS(buf, start, size);
                        onCreateCharacter(socket, (CreateCharacterPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.DeleteCharacter:
                        _packet = new DeleteCharacterPacketCS(buf, start, size);
                        onDeleteCharacter(socket, (DeleteCharacterPacketCS)_packet);
                        break;
                    case (ushort)ClientInPackets.AccountWithAuth:
                        _packet = new AccountWithAuthPacketCS(buf, start, size);
                        onAccountWithAuth(socket, (AccountWithAuthPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.CheckCharacterName:
                        _packet = new CheckCharacterNamePacketCS(buf, start, size);
                        onCheckCharacterName(socket, (CheckCharacterNamePacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Dialog:
                        _packet = new DialogPacketCS(buf, start, size);
                        onDialog(socket, (DialogPacketCS)_packet);
                        break;

                    case (ushort)ClientInPackets.Contact:
                        _packet = new ContactPacketCS(buf, start, size);
                        onContact(socket, (ContactPacketCS)_packet);
                        break;

                    /* 
                           HuntaholicInstanceList = 4000,
                           HuntaholicCreateInstance = 4003,
                           HuntaholicJoinInstance = 4004,
                           HuntaholicLeaveInstance = 4005,
                           HuntaholicLeaveLobby = 4008,
                           CompeteRequest = 4500,
                           CompeteAnswer = 4502,
                           RankingTopRecord = 5000,
                    */
                    case (ushort)ClientInPackets.Report:
                        _packet = new ReportPacketCS(buf, start, size);
                        onReport(socket, (ReportPacketCS)_packet);
                        break;
                    /*

                            ChangeLocation2 = 9000,
                            SecurityNo = 9005,
                     */
                    case (ushort)ClientInPackets.Ping2:
                    case (ushort)ClientInPackets.Unk1:

                        _packet = new PacketIn(buf, start, size);
                        break;
                    /*
                            OpenItemShop = 10000,
                            TakeoutCommercialItem = 10005,
                    */

                    //                 case (ushort) ClientInPackets.HuntaholicLeaveInstance:
                    // 					onHuntaholicLeaveInstance(player, (TakeoutCommercialItemPacketCS)_packet);
                    //                     break;

                    // 		        case (ushort) ClientInPackets.HuntaholicLeaveLobby:
                    // 					onHuntaholicLeaveLobby(player);
                    //                     break;

                    //                 case (ushort) ClientInPackets.CompeteRequest:
                    // 					onCompeteRequest(player, (TakeoutCommercialItemPacketCS)_packet);
                    //                     break;

                    //                 case (ushort) ClientInPackets.CompeteAnswer:
                    // 					onCompeteAnswer(player, (TakeoutCommercialItemPacketCS)_packet);
                    //                     break;

                    //                 case (ushort) ClientInPackets.RankingTopRecord:
                    // 					onRankingTopRecord(player, (TakeoutCommercialItemPacketCS)_packet);
                    //                     break;

                    //                 case (ushort) ClientInPackets.TakeoutCommercialItem:
                    // 					onTakeoutCommercialItem(player, (TakeoutCommercialItemPacketCS)_packet);
                    //                     break;

                    //                case (ushort) ClientInPackets.TakeoutCommercialItem:
                    //                    break;


                    /*
                                    case (ushort)10010:
                                        _packet = new PacketIn(buf, start, size);
                    //                    _packet = new AccountPacketCA(buf, start, size);
                      //                  onAccount(socket, (AccountPacketCA)_packet);
                                        SendAuthComplete(socket, 1);
                                        break;
                    */

                    /*
                                    case (ushort)ClientInPackets.ServerList:
                                        _packet = new ServerListPacketCA(buf, start, size);
                                        onServerList(socket);
                                        break;

                                    case (ushort)ClientInPackets.ServerSelect:
                                        _packet = new ServerSelectPacketCA(buf, start, size);
                                        onServerSelect(socket, (ServerSelectPacketCA)_packet);

                                        break;

                                    case (ushort)ClientInPackets.Packet9999:
                                        _packet = new Unk9999PacketCA(buf, start, size);
                                        break;
                    */

                    default:
                        _packet = new PacketIn(buf, start, size);
                        Globals.Log.Error("Received packet code is not a handled packet! " + socket);
                        Globals.Log.Error(Marshal.ToHexDump(
                                    String.Format("===> <{2}> Packet 0x{0:X2} ({1}) length: {3} (ThreadId={4})", _packet.ID, _packet.ID,
                                                  socket.TcpEndpoint,
                                                  _packet.PacketSize - PacketIn.HDR_SIZE, System.Threading.Thread.CurrentThread.ManagedThreadId),
                                    _packet.ToArray()));
                        break;

                }
                Interlocked.Increment(ref m_nRecvMessageCount);
                Interlocked.Add(ref m_nRecvMessageByte, (int)_packet.PacketSize);
            }
            catch (System.Exception ex)
            {
                Globals.Log.Error("processPacket Exception: {0}", ex);
            }
            return _packet;
        }























        private void onLogin(TCPConnection socket, LoginPacketCS packet)
        {
            if (GameRule.bUseLoginLogoutDebug)
            {
                Globals.Log.Info("LoginLogout_Debug: onLogin ({0})", packet.szName);
            }

            ConnectionTag tag = socket.Tag;
            lock(tag)
            {
                if (tag.szAccountName.Length > 0)
                {
                    // make sure this character belongs to this account
                    if(tag.vCharacterNameList.Contains(packet.szName))
                    {
                        int foundplayerid = Player.FindPlayer(packet.szName);
                        if ( foundplayerid != 0 )
                        {
                            Globals.Log.Info("Login try with a character which is already logged in :{0} [{1}]", packet.szName, tag.szAccountName);
                            Player foundplayer = Player.GetPlayer(packet.szName);
                            if (foundplayer != null)
                            {
                                foundplayer.Save(false);
                                if (foundplayer.IsLogin())
                                {
                                    foundplayer.LogoutNow(1);
                                }
                                if (foundplayer.Connection != null && foundplayer.Connection.Socket.Connected)
                                {
                                    Messages.SendDisconnectDesc(foundplayer.Connection, 0); // Another Login
                                    foundplayer.Connection.Disconnect();
                                }
                            }
                        }
                        tag.player = Player.AllocPlayer();
                        tag.player.Connection = socket;
                        tag.player.SetAccount(tag.nAccountID, tag.szAccountName);
                        tag.bStorageSecurityCheck = false;
                        Messages.SendUrlList(tag.player);

                        DB_Login pa = new DB_Login(socket, packet.szName, tag.nAccountID, tag.player, tag.nPCBangMode, tag.nEventCode, tag.nAge, tag.nContinuousPlayTime, tag.nContinuousLogoutTime);
                        DatabaseProcess p = GameDBManager.dbProcess;
                        GameDBManager.Instance.Push(p, pa);
                        return;
                    }

                    // if it gets here then the character doesn't belong to this account!
                    Globals.Log.Info("Login attempt with a character that belongs to another account detected :{0} [{1}]",packet.szName, tag.szAccountName);
                }
                else
                {
                    Globals.Log.Info("Illegal login attempt detected: {0}",packet.szName);
                }
            }
        }

        private void onTimeSync(TCPConnection socket, TimeSyncPacketCS packet)
        {
            Player player = socket.Tag.player;

            uint ct = Globals.GetArTime();
            player.m_TS.onEcho(ct - packet.time);
            if (player.m_TS.m_vT.Count >= 4)
            {
                PacketOut pak = new PacketOut((ushort)ClientOutPackets.SetTime);
                pak.WriteUInt32(player.m_TS.GetInterval());
                player.Connection.SendTCP(pak);
            }
            else
            {
                Messages.SendTimeSync(player);
            }
        }

        private void onMoveRequest(TCPConnection socket, MoveRequestPacketCS packet)
        {
//             Player player = socket.Tag.player;
// 
//             if (player == null || player.m_nHP == 0 || !player.bIsInWorld || packet.count == 0)
//                 return;
// 
// // .text:0047A9AC var_88          = dword ptr -88h
// // .text:0047A9AC var_84          = dword ptr -84h
// // .text:0047A9AC pos             = ArPosition ptr -80h
// // .text:0047A9AC _lock           = ArcadiaAutoLock ptr -20h
// // .text:0047A9AC wayPoint        = ArPosition ptr  10h
//             ArPosition curPosFromClient;        // 32   20h
// // .text:0047A9AC __lock          = ArcadiaLock ptr  34h
//             uint ct;                            // 56   38h
//             Creature mover;                     // 60   3Ch
// // .text:0047A9AC vMoveInfo       = std::vector<ArPosition,std::allocator<ArPosition> > ptr  40h
// // .text:0047A9AC pMoveInfo       = dword ptr  50h
// // .text:0047A9AC ry              = dword ptr  54h
//             byte speed;                         // 88   58h
// // .text:0047A9AC distance        = dword ptr  5Ch
// // .text:0047A9AC i               = word ptr  60h
// // .text:0047A9AC pClient         = dword ptr  6Ch
// // .text:0047A9AC pMsg            = dword ptr  70h
// // 
// // Data           :   ebp Relative, [0000006C], Param, Type: struct StructPlayer *, pClient
// // Data           :   ebp Relative, [00000070], Param, Type: struct TS_MOVE_REQUEST *, pMsg
// // Data           :   ebp Relative, [00000054], Local, Type: unsigned int, ry
// // Data           :   ebp Relative, [FFFFFF80], Local, Type: struct ArPosition, pos
// // Data           :   ebp Relative, [00000034], Local, Type: struct ArcadiaLock, __lock
// // Data           :   ebp Relative, [00000050], Local, Type: struct TS_MOVE_REQUEST::MOVE_INFO *, pMoveInfo
// // Data           :   ebp Relative, [FFFFFFE0], Local, Type: struct ArcadiaAutoLock, _lock
// // Data           :   ebp Relative, [00000000], Local, Type: struct ArPosition, targetPos
// // Data           :   ebp Relative, [00000058], Local, Type: unsigned char, speed
// // Data           :   ebp Relative, [0000005C], Local, Type: unsigned int, rx
// // Data           :   ebp Relative, [00000010], Local, Type: struct ArPosition, wayPoint
// // Data           :   ebp Relative, [00000040], Local, Type: class std::vector<ArPosition,std::allocator<ArPosition> >, vMoveInfo
// // Data           :   ebp Relative, [FFFFFF90], Local, Type: struct ArPosition, pos
// // Data           :   ebp Relative, [0000005C], Local, Type: float, distance
// // Data           :   ebp Relative, [FFFFFFA0], Local, Type: struct ArPosition, pos
// // Data           :   ebp Relative, [00000060], Local, Type: float, distance
// // Data           :   ebp Relative, [00000020], Local, Type: struct ArPosition, curPosFromClient
// // Data           :   ebp Relative, [00000060], Local, Type: unsigned short, i
// 
// 
// 
//             if (player.m_nHP != 0)
//             {
//                 if (player.bIsInWorld)
//                 {
//                     ct = Globals.GetArTime();
//                     msg = *(v2 + 112);
//                     *(v2 + 56) = ct;
//                     if (packet.count > 0)
//                     {
//                         mover = player as Creature;
// 
//                         speed = (byte)(player.GetMoveSpeed() / 7);
//                         Summon ro = player.GetRideObject();
// 
//                         if (packet.handle == null || packet.handle == player.m_hHandle)
//                             goto LABEL_25;
// 
//                         mover = player.GetSummon(packet.handle);
//                         if (mover != null)
//                         {
//                             if (player.m_nRideIdx != 0 && ro != null && ro.m_hHandle == mover.m_hHandle)
//                             {
//                                 mover = player;
//         LABEL_25:
//                                 if (ro != null)
//                                 {
//                                     speed = ro.GetRidingMoveSpeed();
//                                 }
//         LABEL_27:
//                                 if (mover == null)
//                                 {
//                                     pos_4 = 0;
//                                     pos = 1;
//                                     goto LABEL_96;
//                                 }
//                                 curPosFromClient = new ArPosition(packet.x,packet.y,0);
//                                 if (curPosFromClient.x < 0.0f
//                                   || GameContent.g_nMapWidth < curPosFromClient.x
//                                   || curPosFromClient.y < 0.0f
//                                   || GameContent.g_nMapHeight < curPosFromClient.y
//                                   || mover.mv.GetDistance(curPosFromClient) > 525.0f)
//                                 {
//                                     pos_4 = 0;
//                                     pos = 6;
//                                     goto LABEL_96;
//                                 }
//                                 if (speed < 1)
//                                     speed = 1;
//                                 *(v2 + 68) = 0;
//                                 *(v2 + 72) = 0;
//                                 *(v2 + 76) = 0;
//                                 v9 = packet.count == 0;
//                                 *(v2 + 96) = packet.x;
//                                 *(v2 + 92) = packet.y;
//                                 *(v2 - 4) = 0;
//                                 v17 = packet.x;
//                                 *(v2 + 80) = msg + 1;
//                                 *(v2 + 16) = v17;
//                                 *(v2 + 96) = 0;
//                                 *(v2 + 20) = *(v2 + 92);
//                                 if (packet.count == 0)
//                                     goto LABEL_94;
//                                 while ( 1 )
//                                 {
//                                     if ( (mover->baseclass_0.baseclass_0.baseclass_0.vfptr[1].onProcess)(mover)
//                                       && StructPlayer::IsInDungeon(mover)
//                                       && GameContent::CollisionToLine(*(v2 + 16), *(v2 + 20), **(v2 + 80), *(*(v2 + 80) + 4)) )
//                                     {
//                                         pos_4a = 0;
//                                         posa = 6;
//                                         v61 = msg->baseclass_0.id;
//                                         v60 = player;
//                                         goto LABEL_52;
//                                     }
//                                     v18 = *(v2 + 80);
//                                     *(v2 + 92) = *v18;
//                                     *(v2 + 84) = *(v18 + 4);
//                                     *(v2 + 32) = *(v2 + 92);
//                                     *(v2 + 36) = *(v2 + 84);
//                                     *(v2 + 40) = 0.0;
//                                     v19 = 0.0 < *(v2 + 92);
//                                     v20 = 0.0 == *(v2 + 92);
//                                     *(v2 + 16) = *(v2 + 32);
//                                     *(v2 + 20) = *(v2 + 36);
//                                     *(v2 + 24) = *(v2 + 40);
//                                     *(v2 + 28) = *(v2 + 44);
//                                     if ( !(v19 | v20)
//                                       || g_nMapWidth < *(v2 + 92)
//                                       || *(v2 + 84) < 0.0
//                                       || g_nMapHeight < *(v2 + 84) )
//                                     {
//                                         pos_4a = 0;
//                                         goto LABEL_54;
//                                     }
//                                     std::vector<StructCreature::HateModifier_std::allocator<StructCreature::HateModifier>>::push_back(
//                                         (v2 + 64),
//                                         (v2 + 16));
//                                     ++*(v2 + 96);
//                                     v21 = *(v2 + 96);
//                                     *(v2 + 80) += 8;
//                                     if ( v21 >= msg->count )
//                                         break;
//                                     player = *(v2 + 108);
//                                     mover = *(v2 + 60);
//                                 }
//                                 if ( !*(v2 + 0x44) || ((*(v2 + 0x48) - *(v2 + 0x44)) >> 4) < 1 )
//                                 {
//         LABEL_94:
//                                     std::vector<GameContent::REGEN_INFO_std::allocator<GameContent::REGEN_INFO>>::_Tidy((v2 + 64));
//                                     return;
//                                 }
//                                 v22 = std::vector<StructPlayer::BOOTH_ITEM_INFO_std::allocator<StructPlayer::BOOTH_ITEM_INFO>>::back((v2 + 64));
//                                 v23 = std::vector<StructPlayer::BOOTH_ITEM_INFO_std::allocator<StructPlayer::BOOTH_ITEM_INFO>>::back((v2 + 64));
//                                 if ( !StructCreature::QuadTreeItem::IsCanAdd(*v22, *&v23->cnt) )
//                                 {
//                                     pos_4a = 0;
//                                     posa = 9;
//                                     goto LABEL_55;
//                                 }
//                                 v24 = std::vector<StructPlayer::BOOTH_ITEM_INFO_std::allocator<StructPlayer::BOOTH_ITEM_INFO>>::back((v2 + 64));
//                                 v25 = std::vector<StructPlayer::BOOTH_ITEM_INFO_std::allocator<StructPlayer::BOOTH_ITEM_INFO>>::back((v2 + 64));
//                                 if ( GameContent::IsBlocked(*v24, *&v25->cnt) )
//                                 {
//                                     pos_4a = 0;
//         LABEL_54:
//                                     posa = 6;
//         LABEL_55:
//                                     v61 = msg->baseclass_0.id;
//                                     v60 = *(v2 + 108);
//         LABEL_52:
//                                     SendResult(v60, v61, posa, pos_4a);
//                                     goto LABEL_94;
//                                 }
//                                 v26 = *(v2 + 60);
//                                 *(v2 + 80) = g_nRegionSize;
//                                 v27 = *(v2 + 80);
//                                 v28 = v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                                 *(v2 + 92) = (v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 80));
//                                 v29 = (v28 / v27);
//                                 v30 = msg->y;
//                                 *(v2 + 84) = v29;
//                                 v31 = (v30 / v27);
//                                 v32 = msg->x / v27;
//                                 *(v2 + 96) = v31;
//                                 v33 = *(v2 + 96);
//                                 v34 = *(v2 + 84);
//                                 v35 = *(v2 + 92);
//                                 v36 = ArcadiaServer::Instance();
//                                 ArcadiaServer::_LockArea(
//                                     v36,
//                                     (v2 + 52),
//                                     v35,
//                                     v34,
//                                     v32,
//                                     v33,
//                                     "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                     393);
//                                 while ( 1 )
//                                 {
//                                     *(v2 + 80) = g_nRegionSize;
//                                     if ( *(v2 + 92) == (v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 80)) )
//                                     {
//                                         if ( *(v2 + 84) == (v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y
//                                                           / *(v2 + 80)) )
//                                             break;
//                                     }
//                                     v37 = ArcadiaServer::Instance();
//                                     ArcadiaServer::UnLock(v37, (v2 + 52));
//                                     *(v2 + 80) = g_nRegionSize;
//                                     v38 = *(v2 + 80);
//                                     v39 = v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                                     *(v2 + 92) = (v26->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 80));
//                                     v40 = (v39 / v38);
//                                     v41 = msg->y;
//                                     *(v2 + 84) = v40;
//                                     v42 = (v41 / v38);
//                                     v43 = msg->x / v38;
//                                     *(v2 + 96) = v42;
//                                     v44 = *(v2 + 96);
//                                     v45 = *(v2 + 84);
//                                     v46 = *(v2 + 92);
//                                     v47 = ArcadiaServer::Instance();
//                                     *(v2 + 52) = ArcadiaServer::_LockArea(
//                                                      v47,
//                                                      (v2 + 48),
//                                                      v46,
//                                                      v45,
//                                                      v43,
//                                                      v44,
//                                                      "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                                      402)->handle;
//                                 }
//                                 ArcadiaAutoLock::ArcadiaAutoLock(
//                                     (v2 - 32),
//                                     (v2 + 52),
//                                     "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                     405);
//                                 v48 = *(*(v2 + 108) + 0x44);
//                                 *(v2 - 4) = 1;
//                                 if ( v48 )
//                                 {
//                                     if ( v26->baseclass_0.m_hEnemy )
//                                         (v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[9].onProcess)(v26);
//                                     if ( v26->baseclass_0.m_nMovableTime <= *(v2 + 56) )
//                                     {
//                                         if ( (v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[11].__vecDelDtor)(v26)
//                                           && (v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[12].onProcess)(v26)
//                                           && v26->baseclass_0.baseclass_0.baseclass_0.bIsInWorld )
//                                         {
//                                             ArObject::GetCurrentPosition(
//                                                 &v26->baseclass_0.baseclass_0.baseclass_0,
//                                                 (v2 - 128),
//                                                 msg->cur_time);
//                                             v9 = *(v2 + 68) == 0;
//                                             *(v2 + 8) = 0.0;
//                                             *(v2 + 4) = 0.0;
//                                             *v2 = 0.0;
//                                             *(v2 + 12) = 0.0;
//                                             if ( !v9 )
//                                             {
//                                                 if ( (*(v2 + 72) - *(v2 + 68)) >> 4 )
//                                                 {
//                                                     v49 = std::vector<StructPlayer::BOOTH_ITEM_INFO_std::allocator<StructPlayer::BOOTH_ITEM_INFO>>::back((v2 + 64));
//                                                     *v2 = v49->pItem;
//                                                     *(v2 + 4) = v49->cnt;
//                                                     *(v2 + 8) = LODWORD(v49->gold);
//                                                     *(v2 + 12) = HIDWORD(v49->gold);
//                                                     v26 = *(v2 + 60);
//                                                 }
//                                             }
//                                             v50 = *(v2 + 108);
//                                             if ( v26 != v50
//                                               || (*(v2 + 96) = msg->x,
//                                                   *(v2 + 92) = msg->y,
//                                                   *(v2 - 80) = *(v2 + 96),
//                                                   *(v2 - 76) = *(v2 + 92),
//                                                   *(v2 - 72) = 0.0,
//                                                   g_fMapLength / 5.0 >= ArPosition::GetDistance((v2 - 128), (v2 - 80)))
//                                               || !v50->m_bAutoUsed
//                                               || v50->m_nWorldLocationId != 110900 )
//                                             {
//                                                 if ( !*(v2 + 68)
//                                                   || !((*(v2 + 72) - *(v2 + 68)) >> 4)
//                                                   || (v51 = ArObject::GetCurrentPosition(
//                                                                 &v26->baseclass_0.baseclass_0.baseclass_0,
//                                                                 (v2 - 144),
//                                                                 *(v2 + 56)),
//                                                       g_fMapLength >= ArPosition::GetDistance(v51, v2)) )
//                                                 {
//                                                     if ( v26->baseclass_0.m_StatusFlag.m_flag[0] & 0x10 )
//                                                         v26->baseclass_0.m_StatusFlag.m_flag[0] &= 0xFFFFFFEFu;
//                                                     if ( v26 == v50 )
//                                                     {
//                                                         if ( v50->m_bWarpEnded )
//                                                             v50->m_bWarpEnded = 0;
//                                                     }
//                                                     *(v2 + 96) = msg->x;
//                                                     v52 = *(v2 + 56);
//                                                     *(v2 + 92) = msg->y;
//                                                     *(v2 - 48) = *(v2 + 96);
//                                                     v53 = *(v2 + 88);
//                                                     *(v2 - 44) = *(v2 + 92);
//                                                     *(v2 - 40) = 0.0;
//                                                     v54 = ArcadiaServer::Instance();
//                                                     ArcadiaServer::SetMultipleMove(
//                                                         v54,
//                                                         &v26->baseclass_0.baseclass_0.baseclass_0,
//                                                         (v2 - 48),
//                                                         (v2 + 64),
//                                                         v53,
//                                                         1,
//                                                         v52,
//                                                         1);
//                                                     if ( (v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[1].onProcess)(v26) )
//                                                         *(*(v2 + 108) + 0x1130) = 1;
//                                                     if ( (v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[1].onProcess)(v26) )
//                                                     {
//                                                         if ( v26->m_nRideIdx )
//                                                         {
//                                                             v55 = *(v2 + 56);
//                                                             *(v2 + 108) = msg->x;
//                                                             *(v2 + 96) = msg->y;
//                                                             v56 = *(v2 + 88);
//                                                             *(v2 - 64) = *(v2 + 108);
//                                                             *(v2 - 60) = *(v2 + 96);
//                                                             *(v2 - 56) = 0.0;
//                                                             v57 = StructPlayer::GetRideObject(v26);
//                                                             v58 = ArcadiaServer::Instance();
//                                                             ArcadiaServer::SetMultipleMove(
//                                                                 v58,
//                                                                 v57,
//                                                                 (v2 - 64),
//                                                                 (v2 + 64),
//                                                                 v56,
//                                                                 1,
//                                                                 v55,
//                                                                 1);
//                                                         }
//                                                     }
//                                                     if ( v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[2].GetHandle(v26) )
//                                                     {
//                                                         v59 = ArcadiaServer::Instance();
//                                                         ArcadiaServer::SetObjectPriority(
//                                                             v59,
//                                                             &v26->baseclass_0.baseclass_0.baseclass_0.baseclass_0,
//                                                             UPDATE_PRIORITY_NORMAL);
//                                                     }
//                                                 }
//                                             }
//                                             goto LABEL_93;
//                                         }
//                                         goto LABEL_67;
//                                     }
//                                     if ( !StructCreature::SetPendingMove(&v26->baseclass_0, (v2 + 64), *(v2 + 88)) )
//                                     {
//         LABEL_67:
//                                         SendResult(*(v2 + 108), msg->baseclass_0.id, 5u, 0);
//                                         goto LABEL_93;
//                                     }
//                                 }
//         LABEL_93:
//                                 *(v2 - 4) = 0;
//                                 ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 32));
//                                 goto LABEL_94;
//                             }
//                             v10 = (mover->baseclass_0.baseclass_0.baseclass_0.vfptr[10].__vecDelDtor)(mover);
//                             v9 = msg->speed_sync == 0;
//                             *(v2 + 88) = v10 / 7;
//                             if ( !v9 )
//                             {
//                                 v11 = (player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[10].__vecDelDtor)(
//                                           player,
//                                           v10 % 7);
//                                 *(v2 + 96) = msg->x;
//                                 *(v2 + 92) = msg->y;
//                                 *(v2 - 112) = *(v2 + 96);
//                                 *(v2 - 108) = *(v2 + 92);
//                                 *(v2 - 104) = 0.0;
//                                 *(v2 + 88) = v11 / 7;
//                                 *(v2 + 92) = ArPosition::GetDistance(
//                                                  (v2 - 112),
//                                                  &player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0);
//                                 if ( *(v2 + 92) >= 1800.0 )
//                                 {
//         LABEL_12:
//                                     pos_4 = 0;
//                                     pos = 2;
//         LABEL_96:
//                                     SendResult(&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
//                                     return;
//                                 }
//                                 if ( *(v2 + 92) < 480.0 )
//                                 {
//                                     if ( *(v2 + 92) < 36.0 )
//                                         goto LABEL_24;
//                                     *(v2 + 96) = *(v2 + 88);
//                                     v12 = *(v2 + 96) * 1.2;
//                                 }
//                                 else
//                                 {
//                                     *(v2 + 96) = *(v2 + 88);
//                                     v12 = *(v2 + 96) * 1.5;
//                                 }
//                                 goto LABEL_23;
//                             }
//                         }
//                         else
//                         {
//                             mover = &player->m_pSummonedPet->baseclass_0;
//                             *(v2 + 60) = mover;
//                             if ( mover && mover->baseclass_0.baseclass_0.baseclass_0.vfptr->GetHandle(mover) == msg->handle )
//                             {
//                                 v13 = (player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[10].__vecDelDtor)(player);
//                                 *(v2 + 96) = msg->x;
//                                 *(v2 + 92) = msg->y;
//                                 *(v2 - 96) = *(v2 + 96);
//                                 *(v2 - 92) = *(v2 + 92);
//                                 *(v2 - 88) = 0.0;
//                                 *(v2 + 88) = v13 / 7;
//                                 *(v2 + 96) = ArPosition::GetDistance(
//                                                  (v2 - 96),
//                                                  &player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0);
//                                 if ( *(v2 + 96) >= 1800.0 )
//                                     goto LABEL_12;
//                                 v14 = *(v2 + 88);
//                                 if ( *(v2 + 96) < 120.0 )
//                                 {
//                                     *(v2 + 96) = v14;
//                                     v12 = *(v2 + 96) * 1.1;
//                                 }
//                                 else
//                                 {
//                                     *(v2 + 96) = v14;
//                                     v12 = *(v2 + 96) + *(v2 + 96);
//                                 }
//         LABEL_23:
//                                 *(v2 + 88) = v12;
//                                 goto LABEL_24;
//                             }
//                         }
//         LABEL_24:
//                         if ( mover != player )
//                             goto LABEL_27;
//                         goto LABEL_25;
//                     }
//                 }
//             }
// 
/*
            int v2; // ebp@0
            int v3; // esi@1
            unsigned int v4; // eax@3
            int v5; // ebx@3
            int v6; // eax@4
            StructPlayer *v7; // edi@4
            signed int v8; // eax@4
            bool v9; // zf@4
            signed int v10; // eax@10
            signed int v11; // eax@11
            double v12; // st7@14
            signed int v13; // eax@19
            int v14; // eax@20
            StructSummon *v15; // eax@26
            unsigned __int8 v16; // al@34
            double v17; // st7@36
            int v18; // eax@42
            bool v19; // c0@42
            bool v20; // c3@42
            unsigned __int16 v21; // ax@46
            float *v22; // esi@49
            StructPlayer::BOOTH_ITEM_INFO *v23; // eax@49
            float *v24; // esi@56
            StructPlayer::BOOTH_ITEM_INFO *v25; // eax@56
            int v26; // esi@58
            double v27; // st7@58
            double v28; // st6@58
            unsigned __int64 v29; // qax@58
            double v30; // st6@58
            unsigned __int64 v31; // qax@58
            double v32; // st7@58
            unsigned int v33; // ST10_4@58
            unsigned int v34; // ST08_4@58
            unsigned int v35; // ST04_4@58
            ArcadiaServer *v36; // eax@58
            ArcadiaServer *v37; // eax@61
            double v38; // st7@61
            double v39; // st6@61
            unsigned __int64 v40; // qax@61
            double v41; // st6@61
            unsigned __int64 v42; // qax@61
            double v43; // st7@61
            unsigned int v44; // ST10_4@61
            unsigned int v45; // ST08_4@61
            unsigned int v46; // ST04_4@61
            ArcadiaServer *v47; // eax@61
            char v48; // al@62
            StructPlayer::BOOTH_ITEM_INFO *v49; // eax@73
            int v50; // edi@74
            ArPosition *v51; // eax@80
            unsigned int v52; // ST14_4@86
            int v53; // ST0C_4@86
            ArcadiaServer *v54; // eax@86
            unsigned int v55; // ST14_4@90
            int v56; // ST0C_4@90
            ArObject *v57; // ST00_4@90
            ArcadiaServer *v58; // eax@90
            ArcadiaServer *v59; // eax@92
            ArObject *v60; // [sp+0h] [bp-88h]@51
            unsigned __int16 v61; // [sp+4h] [bp-84h]@51
            unsigned __int16 pos; // [sp+8h] [bp-80h]@12
            unsigned __int16 posa; // [sp+8h] [bp-80h]@50
            int pos_4; // [sp+Ch] [bp-7Ch]@12
            int pos_4a; // [sp+Ch] [bp-7Ch]@50
*/
            Player player = socket.Tag.player;

            if (player == null || player.m_nHP == 0 || !player.bIsInWorld || packet.count == 0)
                return;

            int speed;
            float distance;
            ArPosition pos = player.mv;
            ArPosition npos = new ArPosition();
            ArPosition curPosFromClient = new ArPosition();
            ArPosition wayPoint = new ArPosition();
            List<ArPosition> vMoveInfo = new List<ArPosition>();


            uint ct = Globals.GetArTime();
            speed = (int)player.GetMoveSpeed() / 7;
            Creature mover = (Creature) player;

            if (packet.handle == 0 || packet.handle == player.GetHandle())
            {
                // is the player
                Summon ride = player.GetRideObject();
                if (ride != null)
                {
                    speed = ride.GetRidingMoveSpeed();
                }
            }
            else
            {
                // probably is a summon
                mover = player.GetSummon(packet.handle);
                if (mover != null && mover.GetHandle() == packet.handle)
                {
                    npos.x = packet.x;
                    npos.y = packet.y;
                    npos.z = 0;

                    distance = npos.GetDistance(player.mv);
                    if (distance >= 1800.0f)
                    {
                        Messages.SendResult(socket, packet.ID, 2, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                        return;
                    }

                    if (distance < 120.0f)
                    {
                        speed = (int)((float)speed * 1.1f);
                    }
                    else
                    {
                        speed = (int)((float)speed * 2.0f);
                    }
                }
                else
                {
                    mover = player.m_pSummonedPet;

                    if (mover != null && mover.m_hHandle == packet.handle )
                    {
                        npos.x = packet.x;
                        npos.y = packet.y;
                        npos.z = 0;

                        distance = npos.GetDistance(player.mv);
                        if (distance >= 1800.0f)
                        {
                            Messages.SendResult(socket, packet.ID, 2, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                            return;
                        }
                        if (distance < 120.0f)
                        {
                            speed = (int)((float)speed * 1.1f);
                        }
                        else
                        {
                            speed = (int)((float)speed * 2.0f);
                        }
                    }
                }
            }


            if (mover == null)
            {
                Messages.SendResult(socket, packet.ID, 1, 0);
                return;
            }
            npos.x = packet.x;
            npos.y = packet.y;
            npos.z = 0.0f;
            if (packet.x < 0.0f || GameContent.g_nMapWidth < packet.x || packet.y < 0.0f || GameContent.g_nMapHeight < packet.y || mover.mv.GetDistance(npos) > 525.0f)
            {
                Messages.SendResult(socket, packet.ID, 6, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                return;
            }
            if(speed < 1)
                speed = 1;

            wayPoint.x = packet.x;
            wayPoint.y = packet.y;
            wayPoint.z = 0.0f;
            wayPoint.face = 0.0f;
            if (packet.count == 0)
                return;

            foreach(MoveRequestPacketCS.MoveInfo mi in packet.infos)
            {
                if (mover.IsPlayer() /*&& player.IsInDungeon()*/ && GameContent.CollisionToLine(wayPoint.x, wayPoint.y, mi.tx, mi.ty))
                {
                    Messages.SendResult(socket, packet.ID, 6, 0);
                    return;

                }
                curPosFromClient.x = mi.tx;
                curPosFromClient.y = mi.ty;
                curPosFromClient.z = 0.0f;
                wayPoint.x = curPosFromClient.x;
                wayPoint.y = curPosFromClient.y;
                wayPoint.z = curPosFromClient.z;
                wayPoint.face = curPosFromClient.face;
                if (mi.tx < 0.0f || GameContent.g_nMapWidth < mi.tx || mi.ty < 0.0f || GameContent.g_nMapHeight < mi.ty)
                {
                    Messages.SendResult(socket, packet.ID, 6, 0);
                    return;
                }
                vMoveInfo.Add(wayPoint);
            }

            if (vMoveInfo.Count < 1)
            {
                return;
            }

            ArPosition cp = vMoveInfo.Last();
            if (!Creature.QuadTreeItem.IsCanAdd(cp.x, cp.y))
            {
                Messages.SendResult(socket, packet.ID, 9, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                return;
            }
            if (GameContent.IsBlocked(cp.x, cp.y))
            {
                Messages.SendResult(socket, packet.ID, 6, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                return;
            }

//                             _lock = RappelzServer.Instance._LockArea(mover.mv.x / GameContent.g_nRegionSize,mover.mv.y / GameContent.g_nRegionSize,
//                                 packet.x / GameContent.g_nRegionSize,packet.y / GameContent.g_nRegionSize);
// 
//                             while ( 1 )
//                             {
//                                 if (mover.mv.x / GameContent.g_nRegionSize == (mover.mv.x / GameContent.g_nRegionSize) )
//                                 {
//                                     if ( mover.mv.y / GameContent.g_nRegionSize == (mover.mv.y / GameContent.g_nRegionSize) )
//                                         break;
//                                 }
// 
//                                 RappelzServer.Instance.UnLock(_lock);
// 
//                                 _lock = RappelzServer.Instance._LockArea(mover.mv.x / GameContent.g_nRegionSize,mover.mv.x / GameContent.g_nRegionSize,
//                                     packet.x / GameContent.g_nRegionSize,packet.y / GameContent.g_nRegionSize);
//                             }
//                            ArcadiaAutoLock::ArcadiaAutoLock((v2 - 32),(v2 + 52));

            if (player.bIsInWorld)
            {
                if (mover.m_hEnemy != 0)
                    mover.CancelAttack();
                if (mover.m_nMovableTime <= ct)
                {
                    if (mover.IsActable() && mover.IsMovable() && mover.bIsInWorld)
                    {
                        ArPosition tpos2 = mover.GetCurrentPosition(packet.cur_time);

                        if (vMoveInfo.Count > 0)
                        {
                            cp = vMoveInfo.Last();
                            npos.x = cp.x;
                            npos.y = cp.y;
                            npos.z = cp.z;
                            npos.face = cp.face;
                        }
                        else 
                        {
                            npos.x = 0.0f;
                            npos.y = 0.0f;
                            npos.z = 0.0f;
                            npos.face = 0.0f;
                        }
//                         cp.x = packet.x;
//                         cp.y = packet.y;
//                         cp.z = 0.0f;
                        if (!ReferenceEquals(mover,player) || GameContent.g_fMapLength / 5.0 >= tpos2.GetDistance(cp)
                            || !player.m_bAutoUsed || player.m_nWorldLocationId != 110900 )
                        {
                            if (vMoveInfo.Count < 1 || GameContent.g_fMapLength >= player.GetCurrentPosition(ct).GetDistance(npos))
                            {
                                if ((mover.m_StatusFlag & Rappelz.GameServer.Creature.StatusFlags.MovePending) != 0)
                                    mover.m_StatusFlag &= ~Rappelz.GameServer.Creature.StatusFlags.MovePending;
                                if (ReferenceEquals(mover, player) && player.m_bWarpEnded)
                                    player.m_bWarpEnded = false;
                                npos.x = packet.x;
                                npos.y = packet.y;
                                npos.z = 0.0f;

                                RappelzServer.Instance.SetMultipleMove(mover,npos, vMoveInfo, (sbyte)speed, true, ct, true);
                                if (mover.IsPlayer())
                                    player.m_bMoveReq = true;
                                if (mover.IsPlayer() && player.m_nRideIdx != 0)
                                {
                                    npos.x = packet.x;
                                    npos.y = packet.y;
                                    npos.z = 0.0f;
                                    RappelzServer.Instance.SetMultipleMove(player.GetRideObject(), npos, vMoveInfo, (sbyte)speed, true, ct, true);
                                }
                                if (mover.IsSummon())
                                {
                                    RappelzServer.Instance.SetObjectPriority(mover, SchedulerObject.Priority.Normal);
                                }
                            }
                        }
                        //ArcadiaAutoLock._ArcadiaAutoLock((v2 - 32));
                        return;
                    }
                    Messages.SendResult(socket, packet.ID, 5, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                    //ArcadiaAutoLock._ArcadiaAutoLock((v2 - 32));
                    return;
                }
                if (!mover.SetPendingMove(vMoveInfo, (byte)speed))
                {
//LABEL_67:
                    Messages.SendResult(socket, packet.ID, 5, 0);//&player->baseclass_0.baseclass_0.baseclass_0, msg->baseclass_0.id, pos, pos_4);
                    //ArcadiaAutoLock._ArcadiaAutoLock((v2 - 32));
                    return;

                }
            }
//LABEL_93:
            //ArcadiaAutoLock._ArcadiaAutoLock((v2 - 32));
            return;
        }

        private void onRegionUpdate(TCPConnection socket, RegionUpdatePacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            player.DecRegionUpdateNeedCount();
//             ArPosition pos = player.GetCurrentPosition(Globals.GetArTime());
//             *(v2 - 20) = (player.mv.x / GameContent.g_nRegionSize);
//             v7 = (player.mv.y / GameContent.g_nRegionSize);
//             v8 = *(v2 + 12);
//             v9 = _packet.y;
//             *(v2 - 16) = (player.mv.y / GameContent.g_nRegionSize);
//             v10 = (_packet.y / GameContent.g_nRegionSize);
//             v11 = (_packet.x / GameContent.g_nRegionSize);
//             *(v2 + 8) = v10;
//             v12 = *(v2 - 16);
//             v13 = *(v2 - 20);
//             v14 = (_packet.y / GameContent.g_nRegionSize);

//             RappelzServer.Instance._LockArea((v2 - 24), (_packet.x / GameContent.g_nRegionSize),(_packet.y / GameContent.g_nRegionSize),
//                 (player.mv.x / GameContent.g_nRegionSize),(player.mv.y / GameContent.g_nRegionSize));
//             while ( 1 )
//             {
//                 if ( *(v2 - 20) == (player.mv.x / GameContent.g_nRegionSize) )
//                 {
//                     if ( *(v2 - 16) == (player.mv.y / GameContent.g_nRegionSize) )
//                         break;
//                 }
//                 v16 = ArcadiaServer::Instance();
//                 ArcadiaServer::UnLock(v16, (v2 - 24));
//                 *(v2 + 8) = g_nRegionSize;
//                 v17 = *(v2 + 8);
//                 v18 = v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                 *(v2 - 20) = (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 8));
//                 v19 = (v18 / v17);
//                 v20 = *(v8 + 15);
//                 *(v2 - 16) = v19;
//                 v21 = (v20 / v17);
//                 v22 = *(v8 + 11) / v17;
//                 *(v2 + 8) = v21;
//                 v23 = *(v2 - 16);
//                 v24 = *(v2 - 20);
//                 v25 = *(v2 + 8);
//                 v26 = ArcadiaServer::Instance();
//                 *(v2 - 24) = ArcadiaServer::_LockArea(
//                                  v26,
//                                  (v2 + 12),
//                                  v22,
//                                  v25,
//                                  v24,
//                                  v23,
//                                  "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                  753)->handle;
//             }
//            ArcadiaAutoLock::ArcadiaAutoLock((v2 - 60),(v2 - 24));

            if (player.bIsInWorld)
            {
                Summon ride = player.GetRideObject();
                if (ride != null)
                {
                    RappelzServer.Instance.onRegionChange(ride, _packet.update_time, _packet.bIsStopMessage);
                }
                if (_packet.bIsStopMessage)
                    player.m_bMoveReq = false;
                RappelzServer.Instance.onRegionChange(player, _packet.update_time, _packet.bIsStopMessage);
            }
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 60));
        }

        private void onQuery(TCPConnection socket, QueryPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;


            GameObject obj = GameObject.get(_packet.handle);
            if (obj != null)
            {
                if (obj.bIsInWorld)
                {
                    if (obj.m_layer == player.m_layer)
                    {
                        if (GameContent.IsVisibleRegion((uint)(obj.mv.x / GameContent.g_nRegionSize),
                            (uint)(obj.mv.y / GameContent.g_nRegionSize),
                            (uint)(player.mv.x / GameContent.g_nRegionSize),
                            (uint)(player.mv.y / GameContent.g_nRegionSize)) != 0)
                        {
//                            RLock l = RappelzServer.Instance._LockObjectWithVisibleRange(obj);
//                            AutoLock al = new AutoLock(l.handle);
                            Messages.SendEnterMsg(player, obj);
                        }
                    }
                }
            }
        }

        public void onCheatMessage(Player pClient, string pChat)
        {
            string[] acmd = pChat.Split(new char[] { ' ' }, 2);
            if (acmd == null || acmd.Length < 1)
                return;
            string c2 = acmd[0].Substring(1).ToLower();
            string p = acmd.Length > 1 ? acmd[1] : "";

            SCheatCommand cmd = SCheatCommand.FindCommand(c2);
            if(cmd != null && cmd.CanRun(pChat, pClient.m_nPermission))
            {
                // log it here as well eventually
                cmd.Run(pClient, p);
            }
        }


        private void onChatRequest(TCPConnection socket, ChatRequestPacketCS _packet)
        {
            Player player = socket.Tag.player;
            string pChat;

// .text:0047DCCE it              = StructPlayer::iterator ptr -42Ch
// .text:0047DCCE nWCharCount     = dword ptr -424h
// .text:0047DCCE nReceiverAccountID= dword ptr -420h
// .text:0047DCCE code_page       = dword ptr -41Ch
// .text:0047DCCE pChat           = dword ptr -418h
// .text:0047DCCE var_414         = dword ptr -414h
// .text:0047DCCE var_40C         = dword ptr -40Ch
// .text:0047DCCE pszChatMsg      = word ptr -408h
// .text:0047DCCE var_4           = dword ptr -4
// .text:0047DCCE pClient         = dword ptr  8    8
// .text:0047DCCE pMsg            = dword ptr  12   0Ch
// 
// Data           :   ebp Relative, [00000410], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [00000414], Param, Type: struct TS_CS_CHAT_REQUEST *, pMsg
// Data           :   ebp Relative, [FFFFFFF0], Local, Type: char *, pChat
// Data           :   ebp Relative, [00000000], Local, Type: wchar_t[0x201], pszChatMsg
// Data           :   ebp Relative, [FFFFFFE4], Local, Type: int, nWCharCount
// Data           :   ebp Relative, [FFFFFFEC], Local, Type: int, code_page
// Data           :   ebp Relative, [FFFFFFDC], Local, Type: struct StructPlayer::iterator, it


//             v63 = pszChatMsg ^ __security_cookie;
//             msg = pMsga;
//             v3 = pMsga->len;
//             player = pClienta;
            if (_packet.len <= 255)
            {
                char[] arr = _packet.szMsg.ToCharArray();
//                 v5 = &pMsga[1];
//                 pMsga->szTarget[20] = 0;
//                 *(&msg[1].baseclass_0.size + v3) = 0;
//                 v6 = msg->type == 3;
//                 pChat = &msg[1];
                pChat = _packet.szMsg;
                if (_packet.type != 3 && arr[0] == 47 )
                {
                    onCheatMessage(player, pChat);
                    return;
                }
            
                if ((player.m_StatusFlag & Creature.StatusFlags.Invincible) != 0)
                {
                    player.m_StatusFlag &= ~Creature.StatusFlags.Invincible;
                    if (player.m_pMainSummon != null)
                        player.m_pMainSummon.m_StatusFlag &= ~Creature.StatusFlags.Invincible;
                    if (player.m_pSubSummon != null)
                        player.m_pSubSummon.m_StatusFlag &= ~Creature.StatusFlags.Invincible;
                }
                if (!player.IsChatBlock())
                {
//                     *&pszChatMsg[504] = 0;
//                     *&pszChatMsg[502] = "CodePage";
//                     v9 = ENV();
//                     v10 = XEnvStruct::GetInt(v9, *&pszChatMsg[502], *&pszChatMsg[504]);
//                     *&pszChatMsg[504] = 513;
//                     *&pszChatMsg[502] = pszChatMsg;
//                     *&pszChatMsg[500] = msg->len;
//                     LODWORD(code_page) = v10;
//                     v11 = MultiByteToWideChar(v10, 0, pChat, *&pszChatMsg[500], pszChatMsg, 513);
//                     LODWORD(v12) = 0;
//                     for ( LODWORD(nWCharCount) = v11; SLODWORD(v12) < SLODWORD(nWCharCount); ++LODWORD(v12) )
//                     {
//                         v13 = &pszChatMsg[LODWORD(v12)];
//                         if ( *v13 == 60 )
//                         {
//                             *v13 = 40;
//                         }
//                         else
//                         {
//                             if ( *v13 == 62 )
//                                 *v13 = 41;
//                         }
//                         v11 = LODWORD(nWCharCount);
//                     }
//                     WideCharToMultiByte(LODWORD(code_page), 0, pszChatMsg, v11, pChat, msg->len, 0, 0);
//                     v14 = msg->type;
                    if (_packet.type == 4 )
                    {
                        if (!player.ProcGlobalChatProcess(pChat, 4) )
                            return;
                        Messages.SendGlobalChatMessage(player.m_nPermission > 0 ? 6 : 4, player.GetName(), pChat, 0);
                        ServerLog.LogChat(player.GetAccountID(),player.GetSID(),_packet.type,(int)player.mv.x,(int)player.mv.y,0,0,player.GetAccountName(),player.GetName(),"","",pChat);
                    }
                    else if (_packet.type == 0)
                    {
                        Messages.SendLocalChatMessage(0, player.m_hHandle, pChat,0);
                        ServerLog.LogChat(player.GetAccountID(),player.GetSID(),0,(int)player.mv.x,(int)player.mv.y,0,0,player.GetAccountName(),player.GetName(),"","",pChat);
                    }
                    else if (_packet.type == 3)
                    {
                        Player pTarget = Player.get((uint)Player.FindPlayer(_packet.szTarget)) as Player;

                        if (pTarget != null)
                        {
                            if (!pTarget.IsDenial(player.GetName()))
                            {
                                Messages.SendChatMessage(true, player.m_nPermission > 0 ? 7 : 3,player.GetName(),pTarget,pChat,0);
                                ServerLog.LogChat(player.GetAccountID(),player.GetSID(),(byte)(player.m_nPermission > 0 ? 7 : 3),
                                    (int)player.mv.x,(int)player.mv.y,pTarget.GetAccountID(),pTarget.GetSID(),player.GetAccountName(),player.GetName(),pTarget.GetAccountName(),pTarget.GetName(),pChat);
                                return;
                            }
                            Messages.SendResult(player,_packet.ID,6,0);
                        }
                        else
                        {
                            Messages.SendResult(player,_packet.ID,1,0);
                        }
                        return;
                    }
                    else if (_packet.type == 2)
                    {
                        if (!player.ProcGlobalChatProcess(pChat, 2))
                            return;
                        Messages.SendGlobalChatMessage(2, player.GetName(), pChat,0);
                        ServerLog.LogChat(player.GetAccountID(),player.GetSID(),_packet.type,(int)player.mv.x,(int)player.mv.y,0,0,player.GetAccountName(),player.GetName(),"","",pChat);
                        return;
                    }
                    else if (_packet.type == 1)
                    {
                        if (!player.ProcGlobalChatProcess(pChat, 1))
                            return;

                        Messages.SendYellChatMessage(1, player.m_hHandle, pChat,0);
                        ServerLog.LogChat(player.GetAccountID(),player.GetSID(),_packet.type,(int)player.mv.x,(int)player.mv.y,0,0,player.GetAccountName(),player.GetName(),"","",pChat);
                        return;
                    }

/*
                    v41 = v14 - 10;
                    if ( v41 )
                    {
                        v42 = v41 - 1;
                        if ( !v42 )
                        {
                            v48 = player.m_nGuildId;
                            if (player.m_nGuildId == 0)
                                return;
                            *&pszChatMsg[504] = 0;
                            *&pszChatMsg[502] = pChat;
                            *&pszChatMsg[500] = v48;
                            Messages.SendGuildChatMessage(player.GetName(), player.m_nGuildId, pChat,0);
                            v50 = player->m_nGuildId;
                            goto LABEL_49;
                        }
                        if ( v42 != 1 )
                        {
        LABEL_40:
                            v43 = FileLogHandler::GetFileLogHandler();
                            v44 = *v43;
                            nReceiverAccountID = v43;
                            *&pszChatMsg[504] = player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].GetHandle(player);
                            *&pszChatMsg[502] = "+¯+";
                            *&pszChatMsg[500] = nReceiverAccountID;
                            (*(v44 + 4))(nReceiverAccountID, "+¯+", *&pszChatMsg[504]);
                            *&pszChatMsg[504] = player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].GetHandle(player);
                            *&pszChatMsg[502] = "+¯+";
                            v45 = XConsole::Inst(0);
                            XConsole::Printf(v45, *&pszChatMsg[502], *&pszChatMsg[504]);
                            return;
                        }
                        v46 = player->m_nPartyId;
                        if ( !v46 )
                            return;
                        *&pszChatMsg[504] = pChat;
                        *&pszChatMsg[502] = v46;
                        v47 = player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].GetHandle(player);
                        SendAttackTeamChatMessage(0, 12, v47, *&pszChatMsg[502], *&pszChatMsg[504]);
                    }
                    else
                    {
                        v51 = player->m_nPartyId;
                        if ( !v51 )
                            return;
                        *&pszChatMsg[504] = 0;
                        *&pszChatMsg[502] = pChat;
                        *&pszChatMsg[500] = v51;
                        v52 = player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].GetHandle(player);
                        SendPartyChatMessage(v52, *&pszChatMsg[500], *&pszChatMsg[502], *&pszChatMsg[504]);
                    }
                    v50 = player->m_nPartyId;
        LABEL_49:
                    v53 = player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
                    nReceiverAccountID = v50;
                    LOWORD(v50) = msg->len;
                    code_page = v53;
                    nWCharCount = player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x;
                    *&pszChatMsg[504] = v50;
                    *&pszChatMsg[502] = pChat;
                    *&pszChatMsg[500] = 0;
                    *&pszChatMsg[498] = &unk_5F42BB;
                    *&pszChatMsg[496] = 0;
                    *&pszChatMsg[494] = &unk_5F42BB;
                    v54 = player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr;
                    *&pszChatMsg[492] = -1;
                    *&pszChatMsg[490] = v54[3].GetHandle(player);
                    *&pszChatMsg[488] = -1;
                    *&pszChatMsg[486] = StructPlayer::GetAccountName(player);
                    *&pszChatMsg[484] = 0;
                    *&pszChatMsg[482] = nReceiverAccountID;
                    v32 = code_page;
                    v33 = nWCharCount;
                    goto LABEL_50;
        LABEL_50:
                        *&pszChatMsg[480] = v32;
                        *&pszChatMsg[478] = v33;
                        *&pszChatMsg[476] = 1;
                        goto LABEL_51;
        LABEL_51:
                            *&pszChatMsg[474] = (player->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].onProcess)(player);
                            v55 = StructPlayer::GetAccountID(player);
                            LOG::LogChat(
                                v55,
                                *&pszChatMsg[474],
                                SLOBYTE(pszChatMsg[476]),
                                *&pszChatMsg[478],
                                *&pszChatMsg[480],
                                *&pszChatMsg[482],
                                *&pszChatMsg[484],
                                *&pszChatMsg[486],
                                *&pszChatMsg[488],
                                *&pszChatMsg[490],
                                *&pszChatMsg[492],
                                *&pszChatMsg[494],
                                *&pszChatMsg[496],
                                *&pszChatMsg[498],
                                *&pszChatMsg[500],
                                *&pszChatMsg[502],
                                pszChatMsg[504]);
                            return;
*/

                }
            }


        }

        private void onReturnLobby(TCPConnection socket)
        {
            Player player = socket.Tag.player;

            if (player.CanLogoutNow())
            {
                lock(socket.Tag)
                {
                    socket.Tag.nConnId = player.SetReturnLobbyConnection(socket);
                    socket.Tag.nContinuousPlayTime = player.GetContinuousPlayTime();
                    socket.Tag.player = null;
                    socket.Tag.nContinuousLogoutTime = player.GetContinuousLogoutTime();
                }
                player.LogoutNow(2);
            }
        }

        private void onRequestLogoutTimer(TCPConnection socket, int nMsg)
        {
            ushort res;
            int val;

            Player player = socket.Tag.player;

            if (GameRule.bUseLoginLogoutDebug)
            {
                Globals.Log.Info("onRequestLogoutTimer ({0}, {1})", player.GetAccountName(), player.GetHandle());
            }
            player.m_nLastLogoutRequestedTime = Globals.GetArTime();
            if (player.CanLogoutNow())
            {
                val = 0;
                res = 0;
            }
            else
            {
                val = (int)(GameRule.nLogoutTimer / 100);
                res = 22;
            }
            Messages.SendResult(socket, (ushort)nMsg, res, val);
        }

        private void onLogout(TCPConnection socket, LogoutPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (GameRule.bUseLoginLogoutDebug)
            {
                Globals.Log.Info("onLogout({0}, {1})", player.GetAccountName(), player.GetHandle());
            }
            if (player.CanLogoutNow())
                player.LogoutNowWithAccount(4);
        }

        private void onVersion(TCPConnection socket, VersionPacketCS _packet)
        {

        }

        private void onAttackRequest(TCPConnection socket, AttackRequestPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            Creature creature;

            if (player.m_nHP != 0)
            {
                creature = player as Creature;
                if (_packet.handle != player.m_hHandle)
                    creature = player.GetSummon((int)_packet.handle) as Creature;
                if (creature == null)
                {
                    Messages.SendCantAttackMsg(player, _packet.handle, _packet.target,3);
                    return;
                }

                RLock rl1 = RappelzServer.Instance._LockObjectWithVisibleRange(creature);
                AutoLock al1 = new AutoLock(rl1.handle);

                if (_packet.target == 0)
                {
                    if (creature.m_hEnemy != 0)
                        creature.CancelAttack();
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                    return;
                }
                
                Creature target = Creature.get(_packet.target) as Creature;
                if (target == null)
                {
                    if (creature.m_hEnemy != 0)
                    {
                        creature.EndAttack();
//                        ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                        return;
                    }

                    Messages.SendCantAttackMsg(player, _packet.handle, _packet.target, 1);
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                    return;
                }
//                itTarget = 0;
                if (!creature.IsEnemy(target, false))
                {
                    if (creature.m_hEnemy != 0)
                    {
                        creature.EndAttack();
//                        ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                        return;

                    }
                    Messages.SendCantAttackMsg(player, _packet.handle, _packet.target, 0);
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                    return;
                }
                if ( !creature.IsAttackable() || creature.IsUsingBow() || creature.IsUsingCrossBow() && creature.IsPlayer() && creature.GetBulletCount() < 1)
                {
                    Messages.SendCantAttackMsg(player, _packet.handle, _packet.target, 0);
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                    return;
                }

//                ArcadiaAutoLock::_ArcadiaAutoLock((v3 - 44));
                creature.StartAttack(_packet.target, true);
            }
        }

        private static void onCancelAction(TCPConnection socket, CancelActionPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            AutoLock al = new AutoLock(rl.handle);

            Creature cancellor = player.GetSummon(_packet.handle) as Creature;
            if(cancellor == null || !cancellor.bIsInWorld)
                cancellor = player;
            if (cancellor.m_hHandle == _packet.handle)
            {
                if (cancellor.IsUsingSkill())
                {
                    cancellor.CancelSkill();
                }
                else
                {
                    if (cancellor.m_hEnemy != 0)
                        cancellor.CancelAttack();
                }
            }
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 32));
        }

        private void onPutonItem(TCPConnection socket, PutonItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            if (player.IsItemWearable())
            {
//                 *(&msg.itemLevel[21] + 1) = &result;
//                 v5 = RappelzServer.Instance._LockObjectWithVisibleRange(*(&msg.itemLevel[21] + 1),*(&msg.itemLevel[22] + 1));
//                 ArcadiaAutoLock::ArcadiaAutoLock(&_lock, v5, *&msg.elemental_effect_type[5], *&msg.elemental_effect_type[9]);
                Item ci = Item.FindItem(_packet.item_handle);

                if (ci != null)
                {
                    if (!ci.IsWearable()|| player.FindItemBySID(ci.m_Instance.UID) == null)
                    {
                        Messages.SendResult(socket, _packet.ID, 6, 0);
                        return;
                    }

                    Creature creature = player.GetSummon(_packet.target_handle);
                    if (creature == null)
                        creature = (Creature) player;
                    if (creature.Puton((ItemBase.ItemWearType)_packet.position, ci) == 0)
                    {
                        creature.CalculateStat();
                        Messages.SendResult(socket, _packet.ID, 0, 0);
                        if (creature.IsPlayer())
                        {
                            PacketOut packet2 = new PacketOut((ushort)ClientOutPackets.WearMessage);
                            Messages.GetWearMsg(creature, packet2);
                            socket.SendTCP(packet2);

//                             TS_WEAR_INFO::TS_WEAR_INFO(&msg);
//                             GetWearMsg(v2, &msg);
//                             v12 = v2->baseclass_0.baseclass_0.baseclass_0.layer;
//                             pTarget = g_nRegionSize;
//                             v13 = v2->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                             layer[0] = v12;
//                             v14 = (v13 / pTarget);
//                             v15 = v2->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / pTarget;
//                             *&msg.elemental_effect_type[9] = &msg;
//                             *&msg.elemental_effect_type[1] = __PAIR__(*layer, v14);
//                             *(&msg.itemLevel[23] + 1) = v15;
//                             v16 = ArcadiaServer::Instance();
//                             ArcadiaServer::Broadcast(
//                                 v16,
//                                 *(&msg.itemLevel[23] + 1),
//                                 *&msg.elemental_effect_type[1],
//                                 msg.elemental_effect_type[5],
//                                 *&msg.elemental_effect_type[9]);
                        }
                    }
                    else
                    {
                        Messages.SendResult(socket, _packet.ID, 6, 0);
                    }
                }
                else
                {
                    Globals.Log.Error("onPutonItem() : +¦+¦+¦+¦ + {0}", _packet.item_handle);
                    Messages.SendResult(socket, _packet.ID, 1, (int)_packet.item_handle);
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
            }
            else
            {
                Messages.SendResult(socket, _packet.ID, 5, 0);
            }
        }

        private void onPutoffItem(TCPConnection socket, PutoffItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            if ( !player.IsItemWearable())
            {
                Messages.SendResult(socket, _packet.ID, 5, 0);
                return;
            }
            //*&msg.elemental_effect_type[9] = v3->target_handle;
            Creature creature = (Creature) Creature.get(_packet.target_handle);
            if(creature == null)
            {
//                 if ( v2 == it.baseclass_0.m_pObject
//                   || (*&msg.elemental_effect_type[9] = v3->target_handle, StructPlayer::GetSummon(
//                                                                               v2,
//                                                                               *&msg.elemental_effect_type[9])) )
//                     goto LABEL_7;

                creature = (Creature) player;
            }

//            v6 = RappelzServer.Instance.LockObjectWithVisibleRange(*(&msg.itemLevel[21] + 1),*(&msg.itemLevel[22] + 1));
//            ArcadiaAutoLock::ArcadiaAutoLock(&_lock, v6, *&msg.elemental_effect_type[5], *&msg.elemental_effect_type[9]);

//            LOBYTE(v18) = 1;
            Item curitem = creature.GetWornItem((ItemBase.ItemWearType)_packet.position);
            if (curitem == null)
            {
                Messages.SendResult(socket, _packet.ID, 1, 0);
            }
            else
            {
                ItemBase.ItemWearType wt;
                if (creature.IsSummon())
                    wt = curitem.GetWearType();
                else
                    wt = (ItemBase.ItemWearType)_packet.position;
                ushort por = creature.Putoff(wt);
                creature.CalculateStat();
                Messages.SendResult(socket, _packet.ID, por, 0);
                if (por == 0)
                {
                    if (creature.IsPlayer())
                    {
                        PacketOut packet2 = new PacketOut((ushort)ClientOutPackets.WearMessage);
                        Messages.GetWearMsg(creature, packet2);
                        socket.SendTCP(packet2);

//                         TS_WEAR_INFO::TS_WEAR_INFO(&msg);
//                         GetWearMsg(v2, &msg);
//                         v8 = *(v2 + 172);
//                         *&nRet = g_nRegionSize;
//                         v9 = *(v2 + 28);
//                         layer[0] = v8;
//                         v10 = (v9 / *&nRet);
//                         v11 = *(v2 + 27) / *&nRet;
//                         *&msg.elemental_effect_type[9] = &msg;
//                         *&msg.elemental_effect_type[1] = __PAIR__(*layer, v10);
//                         *(&msg.itemLevel[23] + 1) = v11;
//                         RappelzServer.Instance.Broadcast(x,y,layer,
//                             *(&msg.itemLevel[23] + 1),
//                             *&msg.elemental_effect_type[1],
//                             msg.elemental_effect_type[5],
//                             *&msg.elemental_effect_type[9]);
                    }
                }
            }
//            ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
//            goto LABEL_16;
        }

        private void onTakeItem(TCPConnection socket, TakeItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

// .text:0047B391 resultMsg       = TS_SC_TAKE_ITEM_RESULT ptr -0B4h
// .text:0047B391 var_78          = dword ptr -78h
// .text:0047B391 anonymous_0     = byte ptr -74h
// .text:0047B391 pClient         = dword ptr  4
            long incGold;           // 24   18h
// .text:0047B391 _lock           = ArcadiaAutoLock ptr  20h
            List<Player> vList = new List<Player>();    // 60  3Ch
// .text:0047B391 pet_rx          = dword ptr  4Ch
// .text:0047B391 __lock          = ArcadiaLock ptr  50h
// .text:0047B391 it              = GameObject::iterator ptr  54h
            uint ry;// .text:0047B391 ry              = dword ptr  64h
            uint rx;// .text:0047B391 rx              = dword ptr  68h
// .text:0047B391 pet_ry          = dword ptr  6Ch
            uint drop_duration;
// .text:0047B391 szType          = dword ptr  78h
// .text:0047B391 pMsg            = dword ptr  7Ch
            long nNewGold;          // 16  10
// 
// Data           :   ebp Relative, [00000078], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [0000007C], Param, Type: struct TS_CS_TAKE_ITEM *, pMsg
// Data           :   ebp Relative, [00000064], Local, Type: unsigned int, ry
// Data           :   ebp Relative, [0000006C], Local, Type: unsigned long, drop_duration
// Data           :   ebp Relative, [00000050], Local, Type: struct ArcadiaLock, __lock
// Data           :   ebp Relative, [FFFFFF4C], Local, Type: struct TS_SC_TAKE_ITEM_RESULT, resultMsg
// Data           :   ebp Relative, [00000020], Local, Type: struct ArcadiaAutoLock, _lock
// Data           :   ebp Relative, [00000068], Local, Type: unsigned int, rx
// Data           :   ebp Relative, [00000078], Local, Type: struct StructCreature *, pTaker
// Data           :   ebp Relative, [00000054], Local, Type: struct GameObject::iterator, it
// Data           :   ebp Relative, [0000004C], Local, Type: unsigned int, pet_rx
// Data           :   ebp Relative, [0000006C], Local, Type: unsigned int, pet_ry
// Data           :   ebp Relative, [00000078], Local, Type: const char *, szType
// Data           :   ebp Relative, [00000018], Local, Type: struct StructGold, incGold
// Data           :   ebp Relative, [0000003C], Local, Type: class std::vector<StructPlayer *,std::allocator<StructPlayer *> >, vList
// Data           :   ebp Relative, [0000005C], Local, Type: class std::_Vector_iterator<StructPlayer *,std::allocator<StructPlayer *> >, it
// Data           :   ebp Relative, [00000010], Local, Type: struct StructGold, nNewGold
            RLock rl = null;
            AutoLock al = null;
            Item item = null;
            ArPosition pos;
            int i;
            string pick;

            rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);

            Pet pet = player.m_pSummonedPet;
            // packet v7 = *(v2 + 124);
            Creature picker = player;
            uint ct = Globals.GetArTime();

            if (pet != null && pet.m_hHandle == _packet.taker_handle && (pet.m_ContentInfo.attribute_flag & 4) != 0 && pet.bIsInWorld)
            {
//                 *(v2 + 120) = GameContent.g_nRegionSize;
//                 v8 = (pet.mv.y / GameContent.g_nRegionSize);
//                 *(v2 + 76) = (pet.mv.x / GameContent.g_nRegionSize);
//                 *(v2 + 108) = (pet.mv.y / GameContent.g_nRegionSize);
// 
//                 RappelzServer.Instance.UnLock(rl);
// 
//                 v102 = 1145;
//                 v98 = "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp";
//                 v95 = *(v2 + 108);
//                 for ( i = v2 - 184; ; i = v2 - 152 )
//                 {
//                     v11 = *(v2 + 76);
//                     v12 = *(v2 + 100);
//                     v13 = *(v2 + 104);
//                     v14 = i;
//                     v16 = RappelzServer.Instance._LockArea(v14, v13, v12, v11, v95, v98, v102);
//                     v17 = g_nRegionSize;
//                     *(v2 + 80) = v16->handle;
//                     *(v2 + 120) = v17;
//                     v18 = *(v2 + 120);
//                     if ( *(v2 + 104) == (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 120)) )
//                     {
//                         if ( *(v2 + 100) == (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / v18)
//                           && *(v2 + 76) == (v6->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / v18)
//                           && *(v2 + 108) == (v6->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / v18) )
//                             break;
//                     }
//                     v19 = ArcadiaServer::Instance();
//                     ArcadiaServer::UnLock(v19, (v2 + 80));
//                     *(v2 + 120) = g_nRegionSize;
//                     v20 = *(v2 + 120);
//                     v21 = v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                     *(v2 + 104) = (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 120));
//                     v22 = (v21 / v20);
//                     v23 = v6->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x;
//                     *(v2 + 100) = v22;
//                     v24 = (v23 / v20);
//                     v25 = v6->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / v20;
//                     *(v2 + 76) = v24;
//                     v102 = 1156;
//                     v98 = "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp";
//                     *(v2 + 108) = v25;
//                     v95 = v25;
//                 }
                picker = pet;
            }
            al = new AutoLock(rl.handle);

            if (ReferenceEquals(picker, player))
            {
                if (!player.IsItemPickable())
                {
                    Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                    goto EXIT;
                }
            }
            else if (!ReferenceEquals(picker, pet))
            {
                Messages.SendResult(player, _packet.ID, 3, _packet.item_handle);
                goto EXIT;
            }

            item = GameObject.get(_packet.item_handle) as Item;
            if (item != null)
            {
                if (item.IsItem())
                {
                    if (item != null)
                    {
                        if (player.m_Attribute.nMaxWeight - player.m_fWeight < item.GetWeight())
                        {
                            Messages.SendResult(player, _packet.ID, 11, _packet.item_handle);
                            goto EXIT;
                        }
                        if (item.bIsInWorld)
                        {
                            if (item.m_Instance.OwnerHandle != 0)
                            {
                                Globals.Log.Error("onTakeItem() : OwnerHandle not null. {0} ({1})", player.GetName(), _packet.item_handle);
                                goto EXIT;
                            }

                            if (GameRule.GetPickableRange() < item.mv.GetDistance(picker.GetCurrentPosition(ct)))
                            {
                                Messages.SendResult(player, _packet.ID, 2, _packet.item_handle);
                                goto EXIT;
                            }
                            
                            if (item.IsQuestItem() && !player.IsTakeableQuestItem(item.m_Instance.Code))
                            {
                                Messages.SendResult(player, _packet.ID, 6, _packet.item_handle);
                                goto EXIT;
                            }

                            drop_duration = ct - item.m_nDropTime;

                            ry = 3000;
                            for (i = 0; i < 3; i ++)
                            {
                                if (item.m_ItemPickupOrder.hPlayer[i] == 0 && item.m_ItemPickupOrder.nPartyID[i] == 0)
                                    break;

                                if (item.m_ItemPickupOrder.nPartyID[i] <= 0 || item.m_ItemPickupOrder.nPartyID[i] != player.m_nPartyId)
                                {
                                    if (item.m_ItemPickupOrder.hPlayer[i] != player.m_hHandle)
                                    {
                                        if (drop_duration < ry)
                                        {
                                            Messages.SendResult(player, _packet.ID, 6, _packet.item_handle);
                                            goto EXIT;
                                        }
                                        ry += 1000;
                                    }
                                }
                            }

                            if (item.m_Instance.Code == 0)
                            {
                                if (player.m_nPartyId == 0)
                                {
                                    if (player.m_nGold + item.m_Instance.nCount > Constants.MAX_GOLD_FOR_INVENTORY)
                                    {
                                        Messages.SendResult(player, _packet.ID, 53, _packet.item_handle);
                                        goto EXIT;
                                    }
                                }
                            }

                            PacketOut pak = new PacketOut(ClientOutPackets.TakeItemResult);

                            pak.WriteUInt32(_packet.item_handle);
                            pak.WriteUInt32(picker.m_hHandle);

                            RappelzServer.Instance.Broadcast((uint)(player.mv.x / GameContent.g_nRegionSize),(uint)(player.mv.y / GameContent.g_nRegionSize),
                                player.m_layer, pak);
                            if (GameContent.RemoveItemFromWorld(item))
                            {
                                if (player.m_nPartyId != 0)
                                {
                                    if (item.m_Instance.Code != 0)
                                    {
                                        // actual item
                                        GameContent.procPartyShare(player, item);
                                    }
                                    else
                                    {
                                        // gold
                                        PartyManager.Instance.GetNearMember(player, 400.0f, vList);

                                        incGold = (item.m_Instance.nCount / vList.Count > 0 ? vList.Count : 1);
                                        pick = "PICK";
                                        if (vList.Count == 1)
                                            pick = "PPICK";

                                        foreach(Player np in vList)
                                        {
                                            nNewGold = incGold + np.m_nGold;
                                            if (np.ChangeGold(nNewGold) != 0)
                                            {
                                                Messages.PrintfChatMessage(false, 20, "@SYSTEM", np, "@578");
                                                ServerLog.Log((ushort)0x961, np.GetAccountID(),np.GetSID(),item.m_Instance.nLevel + (100 * item.m_Instance.nEnhance),
                                                    item.m_Instance.Code,0,0,0, nNewGold, (long)player.mv.x,(long)player.mv.y,0, np.GetAccountName(),np.GetName(),"",pick);

                                            }
                                            else
                                            {
                                                ServerLog.Log((ushort)0x961, np.GetAccountID(),np.GetSID(),item.m_Instance.nLevel + (100 * item.m_Instance.nEnhance),
                                                    item.m_Instance.Code,0,0,incGold,nNewGold,(long)player.mv.x,(long)player.mv.y,0,np.GetAccountName(),np.GetName(),"",pick);
                                            }
                                        }
                                        Item.PendFreeItem(item);
                                    }
                                    goto EXIT;
                                }
                                uint nih = GameContent.procAddItem(player, item, false);
                                if (nih != 0)
                                {
                                    Messages.SendResult(player, 204, 0, nih);
                                    goto EXIT;
                                }
                                Item.PendFreeItem(item);
                                Messages.SendResult(player, 0xCC, 6, (int)_packet.item_handle);
                                goto EXIT;
                            }
                        }
                    }
                }
            }
            //Messages.SendResult(player, v96, v100, v104);
            Messages.SendResult(player,  _packet.ID, 1, _packet.item_handle);
EXIT:
            ;
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 + 32));
        }

        private void onEraseItem(TCPConnection socket, EraseItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (player.IsActable())
            {
                PacketOut pak = new PacketOut(ClientOutPackets.ItemDestroyResult);
                RLock rl = RappelzServer.Instance._LockObject(player);
                AutoLock al = new AutoLock(rl.handle);
                pak.WriteByte((byte)_packet.count);
                for(int i = 0; i < _packet.count; ++i)
                {
                    Item item = Item.FindItem(_packet.handles[i]);
                    if (item != null)
                    {
                        player.EraseItem(item, _packet.counts[i]);
//                        Messages.SendResult(player, _packet.ID, 0, 0);
                    }
                    pak.WriteUInt32(_packet.handles[i]);
                    pak.WriteInt64(_packet.counts[i]);
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 40));
                player.Connection.SendTCP(pak);
            }
            else
            {
                Messages.SendResult(player, _packet.ID, 5,0);
            }

        }

        private void onStorage(TCPConnection socket, StoragePacketCS _packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

// .text:00476FEF result          = ArcadiaLock ptr -0FCh
// .text:00476FEF n8              = qword ptr -0F8h
// .text:00476FEF n7              = qword ptr -0F0h
// .text:00476FEF n6              = qword ptr -0E8h
// .text:00476FEF var_E0          = qword ptr -0E0h
// .text:00476FEF var_D8          = dword ptr -0D8h
// .text:00476FEF var_D4          = dword ptr -0D4h
// .text:00476FEF var_D0          = qword ptr -0D0h
// .text:00476FEF n4              = qword ptr -0C8h
// .text:00476FEF var_C0          = dword ptr -0C0h
// .text:00476FEF var_BC          = dword ptr -0BCh
// .text:00476FEF var_B8          = dword ptr -0B8h
// .text:00476FEF var_B4          = dword ptr -0B4h
// .text:00476FEF var_B0          = dword ptr -0B0h
// .text:00476FEF var_AC          = dword ptr -0ACh
// .text:00476FEF n9              = qword ptr -0A8h
// .text:00476FEF var_A0          = dword ptr -0A0h
// .text:00476FEF var_9C          = dword ptr -9Ch
// .text:00476FEF n3              = qword ptr -98h
// .text:00476FEF var_90          = dword ptr -90h
// .text:00476FEF var_8C          = dword ptr -8Ch
// .text:00476FEF n5              = qword ptr -88h
// .text:00476FEF var_80          = dword ptr -80h
// .text:00476FEF var_7C          = dword ptr -7Ch
// .text:00476FEF var_78          = dword ptr -78h
// .text:00476FEF var_70          = dword ptr -70h
// .text:00476FEF var_6C          = dword ptr -6Ch
// .text:00476FEF var_68          = dword ptr -68h
// .text:00476FEF n2              = qword ptr -64h
// .text:00476FEF _lock           = ArcadiaAutoLock ptr -5Ch
// .text:00476FEF cnt             = qword ptr -48h
// .text:00476FEF gold            = qword ptr -40h
// .text:00476FEF rhs             = StructGold ptr -38h
// .text:00476FEF nGold           = qword ptr -30h
// .text:00476FEF anonymous_0     = StructGold ptr -28h
// .text:00476FEF var_4           = dword ptr -4
// .text:00476FEF pClient         = dword ptr  8
// .text:00476FEF pMsg            = dword ptr  0Ch
// 
// Data           :   ebp Relative, [00000074], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [00000078], Param, Type: struct TS_CS_STORAGE *, pMsg
// Data           :   ebp Relative, [00000010], Local, Type: struct ArcadiaAutoLock, _lock
            Item pItem;         // Data           :   ebp Relative, [00000048], Local, Type: struct StructItem *, pItem
            long nStorageGold;  // Data           :   ebp Relative, [00000044], Local, Type: struct StructGold, nStorageGold
            long nGold;         // Data           :   ebp Relative, [0000003C], Local, Type: struct StructGold, nGold

            RLock rl;
            AutoLock al;

            try
            {
                rl = RappelzServer.Instance._LockObject(player);
                al = new AutoLock(rl.handle);

                if (!player.m_bIsUsingStorage)
                {
                    Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                    return;
                }

                if (_packet.mode == 4)
                {
                    player.CloseStorage();
                    return;
                }
                if (!player.m_bIsUsingStorage
                  || !player.IsActable()
                  || player.m_hTradeTarget != 0
                  || player.IsUsingSkill())
                {
            LABEL_64:
                    Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                    return;

                }

                if (_packet.mode != 0 && _packet.mode != 1 )
                {
                    if (_packet.mode == 2)
                    {
                        if (_packet.count > 0)
                        {
                            if (player.m_nGold >= _packet.count)
                            {
                                if (player.m_nStorageGold + _packet.count > Constants.MAX_GOLD_FOR_STORAGE)
                                {
                                    Messages.PrintfChatMessage(false, 20, "@SYSTEM", player, "@575\v#@gold@#\v{0}", _packet.count);
                                    Messages.SendResult(player, _packet.ID,0x35, _packet.item_handle);
                                    return;
                                }
                                nGold = player.m_nGold;

                                if (player.ChangeGold(nGold - _packet.count) == 0)
                                {
                                    if (player.ChangeStorageGold(player.m_nStorageGold + _packet.count) == 0)
                                    {
                                        player.Save(true);
                                        // LOGGING NEEDED HERE
                                        return;
                                    }
                                }
                                if (player.ChangeGold(nGold) != 0)
                                {
    /*
                                    v84 = HIDWORD(_packet.count);
                                    v20 = player.baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr;
                                    v83 = LODWORD(_packet.count);
                                    *(&v81 + 4) = v81;
                                    *(&nGold + 4) = nGold;
                                    LODWORD(nGold) = v20[3].GetHandle(player);
                                    HIDWORD(rhs.m_nGold) = "ChangeGold/ChangeStorageGold Failed: Case[0], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]\n";
                                    v21 = XConsole::Inst(0);
                                    XConsole::Printf(v21, HIDWORD(rhs.m_nGold), nGold, v81.m_nGold, v82, v83, v84);
                                    v22 = FileLogHandler::GetFileLogHandler();
                                    v84 = HIDWORD(_packet.count);
                                    v23 = v22.vfptr;
                                    v83 = LODWORD(_packet.count);
                                    HIDWORD(cnt) = v22;
                                    v24 = player.baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr;
                                    *(&v81 + 4) = v81;
                                    *(&nGold + 4) = nGold;
                                    LODWORD(nGold) = v24[3].GetHandle(player);
                                    rhs.m_nGold = __PAIR__(
                                                      "ChangeGold/ChangeStorageGold Failed: Case[0], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]",
                                                      HIDWORD(cnt));
                                    (v23.LogString)(
                                        HIDWORD(cnt),
                                        "ChangeGold/ChangeStorageGold Failed: Case[0], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]",
                                        nGold,
                                        v81.m_nGold,
                                        v82,
                                        v83,
                                        v84);
    */
                                }

                                Messages.SendResult(player, _packet.ID, 53, _packet.item_handle);
                                return;

                            }
                        }
                    }
                    else
                    {
                        if (_packet.mode != 3 )
                            return;
                        nGold = player.m_nGold;
                        if (_packet.count > 0)
                        {
                            if (player.m_nStorageGold <= _packet.count)
                            {
                                if (nGold + _packet.count > Constants.MAX_GOLD_FOR_INVENTORY)
                                {
                                    Messages.PrintfChatMessage(false, 20, "@SYSTEM", player, "@576\v#@gold@#\v{0}", _packet.count);
                                    Messages.SendResult(player, _packet.ID, 0x35, _packet.item_handle);
                                    return;
                                }
                                if (player.ChangeStorageGold(player.m_nStorageGold - _packet.count) == 0)
                                {
                                    if (player.ChangeGold(nGold + _packet.count) == 0)
                                    {
                                        player.Save(true);
                                        // LOGGING NEEDED HERE
                                        return;
                                    }
                                }
                                if (player.ChangeStorageGold(player.m_nStorageGold) != 0)
                                {
    /*
                                    v84 = HIDWORD(_packet.count);
                                    v36 = player.baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr;
                                    v83 = *v25;
                                    *(&v81 + 4) = v81;
                                    *(&nGold + 4) = nGold;
                                    LODWORD(nGold) = v36[3].GetHandle(player);
                                    HIDWORD(rhs.m_nGold) = "ChangeGold/ChangeStorageGold Failed: Case[1], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]\n";
                                    v37 = XConsole::Inst(0);
                                    XConsole::Printf(v37, HIDWORD(rhs.m_nGold), nGold, v81.m_nGold, v82, v83, v84);
                                    v38 = FileLogHandler::GetFileLogHandler();
                                    v84 = HIDWORD(_packet.count);
                                    HIDWORD(cnt) = v38;
                                    v83 = *v25;
                                    v39 = v38.vfptr;
                                    *(&v81 + 4) = v81;
                                    HIDWORD(rhs.m_nGold) = v39 + 4;
                                    v40 = player.baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr;
                                    *(&nGold + 4) = nGold;
                                    LODWORD(nGold) = v40[3].GetHandle(player);
                                    v41 = HIDWORD(rhs.m_nGold);
                                    rhs.m_nGold = __PAIR__(
                                                      "ChangeGold/ChangeStorageGold Failed: Case[1], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]",
                                                      HIDWORD(cnt));
                                    (*v41)(
                                        HIDWORD(cnt),
                                        "ChangeGold/ChangeStorageGold Failed: Case[1], Player[%s], Info[Inven(%I64d), Storage(%I64d), Move(%I64d)]",
                                        nGold,
                                        v81.m_nGold,
                                        v82,
                                        v83,
                                        v84);
    */
                                }
                                Messages.SendResult(player, _packet.ID, 53, _packet.item_handle);
                                return;

                            }
                        }
                    }
                    Messages.SendResult(player, _packet.ID, 10, _packet.item_handle);
                    return;
                }

                if (_packet.count <= 0)
                {
                    Messages.SendResult(player, _packet.ID, 10, _packet.item_handle);
                    return;
                }

                pItem = Item.FindItem(_packet.item_handle);

                if (pItem == null)
                {
                    Messages.SendResult(player, _packet.ID, 1, _packet.item_handle);
                    return;
                }
                if (pItem.m_Instance.OwnerHandle != player.m_hHandle)
                {
                    Messages.SendResult(player, _packet.ID, 6, _packet.item_handle);
                    return;
                }

                if (pItem.IsInInventory() && _packet.mode == 0)
                {
                    if (player.GetStorageItemCount() >= GameRule.nMaxStorageItemCount )
                    {
                        if ((pItem.m_Instance.Flag & 0x40) == 0
                          || player.FindStorageItem(pItem.m_Instance.Code) == null)
                        {
                            Messages.SendResult(player, _packet.ID, 11, _packet.item_handle);
                            return;
                        }
                    }
                    player.MoveInventoryToStorage(pItem, _packet.count);
                }
                if (pItem.IsInStorage())
                {
                    if (_packet.mode == 1)
                        player.MoveStorageToInventory(pItem, _packet.count);
                }
                player.Save(true);
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
//            ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
            }
        }

        private void onSellItem(TCPConnection socket, SellItemPacketCS _packet)
        {
            long uid;                   
            long nResultCount;          
            long nPrevGold;             
            int nEnhanceLevel;          
            long nPrice;                
            int code;                   
            RLock rl;
            AutoLock al;

            Player player = socket.Tag.player;
            if (player == null)
                return;

            rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            al = new AutoLock(rl.handle);

            try
            {
                Item item = Item.FindItem(_packet.handle);
                if (item == null || item.m_Instance.OwnerHandle != player.m_hHandle)
                {
                    Messages.SendResult(player, _packet.ID, 1, 0);
                    return;
                }
                if (_packet.sell_count == 0)
                {
                    Messages.SendResult(player, _packet.ID, 7, 0);
                    return;
                }

                if (!player.IsSellable(item) || item.m_Instance.nCount < _packet.sell_count)
                {
                    Messages.SendResult(player, _packet.ID, 6, 0);
                    return;
                }

                nPrice = GameRule.GetItemSellPrice(item.m_pItemBase.nPrice, item.GetItemRank(), item.m_Instance.nLevel, item.m_Instance.Code >= 602700 && item.m_Instance.Code <= 602799);

                nResultCount = item.m_Instance.nCount - _packet.sell_count;
                nEnhanceLevel = (item.m_Instance.nLevel + 100 * item.m_Instance.nEnhance);

                if (nResultCount < 0)
                {
                    Messages.SendResult(player, 252, 1, item.m_Instance.Code);
                    return;
                }

                if (player.m_nGold + _packet.sell_count * nPrice > Constants.MAX_GOLD_FOR_INVENTORY)
                {
                    Messages.SendResult(player, 252, 53, item.m_Instance.Code);
                    return;
                }
                if (!player.EraseItem(item, item.m_Instance.Code))
                {
                    Messages.SendResult(player, 252, 5, item.m_Instance.Code);
                    return;
                }

                nPrevGold = player.m_nGold;
                if (player.ChangeGold(player.m_nGold + _packet.sell_count * nPrice) != 0)
                {
                    ServerLog.Log((ushort)0x965,player.GetAccountID(),player.GetSID(),nEnhanceLevel,item.m_Instance.Code,_packet.sell_count,
                        nResultCount, _packet.sell_count * nPrice, player.m_nGold, player.GetLastContactLong("npc"), nPrevGold, item.m_Instance.UID,
                        player.GetAccountName(),player.GetName(),"","");
                    Messages.SendResult(player, 252, 53, item.m_Instance.Code);
                }
                else
                {
                    ServerLog.Log((ushort)0x965,player.GetAccountID(),player.GetSID(),nEnhanceLevel,item.m_Instance.Code,_packet.sell_count,
                        nResultCount, _packet.sell_count * nPrice, player.m_nGold, player.GetLastContactLong("npc"), nPrevGold, item.m_Instance.UID,
                        player.GetAccountName(),player.GetName(),"","");

                    Messages.SendResult(player, 252, 0, item.m_Instance.Code);

                    PacketOut pak = new PacketOut(ClientOutPackets.NpcTradeInfo);

                    pak.WriteByte(1);
                    pak.WriteInt32(item.m_Instance.Code);
                    pak.WriteInt64(_packet.sell_count);
                    pak.WriteInt64(_packet.sell_count * nPrice);
                    pak.WriteInt32(0);
                    pak.WriteUInt32(player.GetLastContactLong("npc"));
                    player.Connection.SendTCP(pak);
                }
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 + 32));
            }


        }

        private void onPutOnCard(TCPConnection socket, PutonCardPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (!player.IsItemWearable())
            {
                Messages.SendResult(player, _packet.ID, 5, 0);
                return;
            }

            Item pItem = Item.FindItem(_packet.item_handle);
            if (pItem != null)
            {
                if (player.FindItemBySID(pItem.m_Instance.UID) == null)
                {
                    Messages.SendResult(player, _packet.ID, 6, 0);
                    return;
                }

                RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                AutoLock al = new AutoLock(rl.handle);
                if (player.PutOnBelt(_packet.pos, pItem))
                {
                    player.CalculateStat();
                    Messages.SendBeltSlotInfo(player);
                }
                else
                {
                    Messages.SendResult(player, _packet.ID, 6, 0);
                }
            }
            else
            {
                Globals.Log.Error("onPutonItem() : Invalid Handle: {0}", _packet.item_handle);
                Messages.SendResult(player, _packet.ID, 1, _packet.item_handle);
            }
        }

        private void onPutOffCard(TCPConnection socket, PutoffCardPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (player.IsItemWearable() )
            {
                RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                AutoLock al = new AutoLock(rl.handle);

                player.PutOffBelt(_packet.pos);
                player.CalculateStat();
                Messages.SendBeltSlotInfo(player);
            }
            else
            {
                Messages.SendResult(player, _packet.ID,5,0);
            }
        }

        private void onArrangeItem(TCPConnection socket, ArrangeItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            RLock rl = RappelzServer.Instance._LockObject(player);
            AutoLock al = new AutoLock(rl.handle);

            ushort res = player.ArrangeItem(_packet.bIsStorage);
            Messages.SendResult(player, _packet.ID, res, (int) (_packet.bIsStorage ? 1 : 0));
            if (res == 0)
                Messages.SendItemList(player, _packet.bIsStorage);
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 36));

        }

        private void onBuyItem(TCPConnection socket, BuyItemPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

// .text:00475DA0 trade_info_msg  = TS_SC_NPC_TRADE_INFO ptr -0FCh
// .text:00475DA0 _lock           = ArcadiaAutoLock ptr -0D8h
// .text:00475DA0 n1              = qword ptr -0C4h
// .text:00475DA0 n8              = qword ptr -0BCh
// .text:00475DA0 var_B4          = qword ptr -0B4h
// .text:00475DA0 n10             = qword ptr -0ACh
// .text:00475DA0 n6              = qword ptr -0A4h
// .text:00475DA0 n5              = qword ptr -9Ch
// .text:00475DA0 elemental_effect_expire_time= qword ptr -94h
// .text:00475DA0 n7              = qword ptr -8Ch
// .text:00475DA0 n2              = qword ptr -84h
// .text:00475DA0 var_7C          = dword ptr -7Ch
// .text:00475DA0 var_74          = dword ptr -74h
            long cnt;// .text:00475DA0 cnt             = qword ptr -70h
// .text:00475DA0 n3              = qword ptr -68h
// .text:00475DA0 n4              = qword ptr -60h
// .text:00475DA0 n9              = qword ptr -58h
// .text:00475DA0 this            = StructGold ptr -50h
// .text:00475DA0 pItem           = dword ptr -48h
            long uid;                   //             = qword ptr -44h
// .text:00475DA0 it              = std::_Vector_iterator<_MARKET_INFO::_MARKET_TAG,std::allocator<_MARKET_INFO::_MARKET_TAG> > ptr -3Ch
            long nTotalPrice;           //     = StructGold ptr -34h
            bool bJoinable = true;      //       = byte ptr -29h
            Item pItem = null;
            Item pNewItem = null;       // -40  -28h
// .text:00475DA0 i               = qword ptr -24h
// .text:00475DA0 anonymous_0     = qword ptr -1Ch
// .text:00475DA0 var_4           = dword ptr -4
// .text:00475DA0 pClient         = dword ptr  8
// .text:00475DA0 pMsg            = dword ptr  0Ch
// 
// Data           :   ebp Relative, [00000078], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [0000007C], Param, Type: struct TS_CS_BUY_ITEM *, pMsg
            string szMarketName;        // Data           :   ebp Relative, [00000050], Local, Type: class std::basic_string<char,std::char_traits<char>,std::allocator<char> >, strMarketName
// Data           :   ebp Relative, [FFFFFF98], Local, Type: struct ArcadiaAutoLock, _lock
// Data           :   ebp Relative, [00000034], Local, Type: class std::_Vector_iterator<_MARKET_INFO::_MARKET_TAG,std::allocator<_MARKET_INFO::_MARKET_TAG> >, it
// Data           :   ebp Relative, [0000002C], Local, Type: __int64, uid
// Data           :   ebp Relative, [00000047], Local, Type: bool, bJoinable
// Data           :   ebp Relative, [0000003C], Local, Type: struct StructGold, nTotalPrice
// Data           :   ebp Relative, [FFFFFF74], Local, Type: struct TS_SC_NPC_TRADE_INFO, trade_info_msg
// Data           :   ebp Relative, [0000004C], Local, Type: int, nTotalHuntaholicPoint
// Data           :   ebp Relative, [0000004C], Local, Type: struct StructItem *, pNewItem
// Data           :   ebp Relative, [00000028], Local, Type: struct StructItem *, pItem
// Data           :   ebp Relative, [0000004C], Local, Type: int, i
// Data           :   ebp Relative, [00000048], Local, Type: struct StructItem *, pNewItem
// Data           :   ebp Relative, [00000028], Local, Type: struct StructItem *, pItem

            RLock rl;
            AutoLock al;


            rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            al = new AutoLock(rl.handle);

            try
            {
                szMarketName = player.GetLastContactMarket();
                if (_packet.buy_count == 0)
                {
                    Messages.SendResult(player, _packet.ID, 7, 0);
                }
                else
                {
                    MarketInfo market = GameContent.GetMarketInfo(szMarketName);
                    if (market != null)
                    {
                        foreach (MarketInfo.MarketTag mt in market.vItemList)
                        {
                            if (mt.code == _packet.item_code)
                            {
                                if ((Item.GetItemBase(_packet.item_code).Flag & 0x40) != 0)
                                {
                                    bJoinable = true;
                                }
                                else
                                {
                                    bJoinable = false;
                                    if (_packet.buy_count != 1)
                                        _packet.buy_count = 1;
                                }
                                nTotalPrice = _packet.buy_count;
                                nTotalPrice *= mt.price;


                                if (nTotalPrice / _packet.buy_count != mt.price || player.m_nGold < nTotalPrice)
                                {
                                    Messages.SendResult(player, _packet.ID, 10, 0);
                                    return;
                                }
                                else
                                {
                                    nTotalPrice = _packet.buy_count;
                                    nTotalPrice *= mt.huntaholic_point;
                                    if (nTotalPrice / _packet.buy_count != mt.huntaholic_point || player.GetHuntaholicPoint() < nTotalPrice)
                                    {
                                        Messages.SendResult(player, _packet.ID, 58, _packet.item_code);
                                        return;
                                    }
                                    ItemBaseServer ibs = Item.GetItemBase(mt.code);
                                    if (player.m_Attribute.nMaxWeight - player.m_fWeight < ibs.fWeight * _packet.buy_count)
                                    {
                                        Messages.SendResult(player, _packet.ID, 11, _packet.item_code);
                                        return;
                                    }
                                    uid = 0;
                                    nTotalPrice = _packet.buy_count;

                                    if (player.ChangeGold(player.m_nGold - mt.price * nTotalPrice) == 0)
                                    {
                                        if (mt.huntaholic_point != 0)
                                        {
                                            player.SetHuntaholicPoint(player.GetHuntaholicPoint() - mt.huntaholic_point * _packet.buy_count);
                                        }

                                        if (bJoinable)
                                        {
                                            cnt = _packet.buy_count;
                                            pItem = Item.AllocItem(0, mt.code, _packet.buy_count, ItemInstance.GenerateCode.ByMarket, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                                            pNewItem = player.PushItem(pItem, pItem.m_Instance.nCount, false);

                                            if (pNewItem != null)
                                                uid = pNewItem.m_Instance.UID;
                                            else
                                                uid = 0;

                                            ServerLog.Log((ushort)0x964, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nLevel + 100 * pItem.m_Instance.nEnhance,
                                                _packet.item_code, _packet.buy_count, pNewItem.m_Instance.nCount, mt.price * _packet.buy_count, player.m_nGold, player.GetLastContactLong("npc"),
                                                mt.huntaholic_point * _packet.buy_count, uid, player.GetAccountName(), player.GetName(), "", "");
                                            if (pNewItem.m_hHandle != pItem.m_hHandle)
                                                Item.PendFreeItem(pItem);
                                        }
                                        else
                                        {
                                            for (int i = 0; i < _packet.buy_count; ++i)
                                            {
                                                pItem = Item.AllocItem(0, _packet.item_code, 1, ItemInstance.GenerateCode.ByMarket, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                                                pNewItem = player.PushItem(pItem, pItem.m_Instance.nCount, false);
                                                if (pNewItem != null)
                                                    uid = pItem.m_Instance.UID;
                                                else
                                                    uid = 0;
                                                ServerLog.Log((ushort)0x964, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nLevel + 100 * pItem.m_Instance.nEnhance,
                                                    _packet.item_code, _packet.buy_count, pNewItem.m_Instance.nCount, mt.price * _packet.buy_count, player.m_nGold,
                                                    player.GetLastContactLong("npc"), mt.huntaholic_point * _packet.buy_count, uid, player.GetAccountName(), player.GetName(), "", "");

                                                if (pNewItem.m_hHandle != pItem.m_hHandle)
                                                    Item.PendFreeItem(pItem);
                                            }
                                        }

                                        Messages.SendResult(player, _packet.ID, 0, _packet.item_code);

                                        PacketOut pak = new PacketOut(ClientOutPackets.NpcTradeInfo);
                                        pak.WriteByte(0);
                                        pak.WriteInt32(_packet.item_code);
                                        pak.WriteInt64(_packet.buy_count);
                                        pak.WriteInt64(mt.price);
                                        pak.WriteInt64(mt.huntaholic_point);
                                        pak.WriteUInt32(player.GetLastContactLong("npc"));

                                        player.Connection.SendTCP(pak);
                                        return;
                                    }
                                }

                                Messages.SendResult(player, _packet.ID, 10, _packet.item_code);
                                return;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
                //            ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
            }
        }


        private void onUseItem(TCPConnection socket, UseItemPacketCS _packet)
        {
// .text:0047697A msg             = TS_SC_USE_ITEM_RESULT ptr -40h
// .text:0047697A _lock           = ArcadiaAutoLock ptr -30h
// .text:0047697A pClient         = dword ptr  4
// .text:0047697A nItemUID        = qword ptr  8
// .text:0047697A nItemEnhanceAndLevel= qword ptr  18h
// .text:0047697A nItemCode       = dword ptr  28h
            int nTargetID;                  // 48   30h
// .text:0047697A nItemCount      = qword ptr  34h
// .text:0047697A rx2             = dword ptr  40h
// .text:0047697A ry1             = dword ptr  48h
// .text:0047697A ry2             = dword ptr  4Ch
// .text:0047697A __lock          = ArcadiaLock ptr  50h
// .text:0047697A rx1             = dword ptr  60h
            int nTargetType;                // 100  64h
// .text:0047697A it              = StructCreature::iterator ptr  68h
            GameObject pObj = null;         // 120  78h
// .text:0047697A pMsg            = dword ptr  7Ch

            int nResult;
            Creature cr = null;
            RLock rl;
            AutoLock al;

// 
// 
// Data           :   ebp Relative, [00000078], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [0000007C], Param, Type: struct TS_CS_USE_ITEM *, pMsg
// Data           :   ebp Relative, [00000028], Local, Type: const int, nItemCode
// Data           :   ebp Relative, [00000008], Local, Type: const __int64, nItemUID
// Data           :   ebp Relative, [00000018], Local, Type: const __int64, nItemEnhanceAndLevel
// Data           :   ebp Relative, [0000007B], Local, Type: const bool, bDecreaseCount
// Data           :   ebp Relative, [FFFFFFC0], Local, Type: struct TS_SC_USE_ITEM_RESULT, msg
// Data           :   ebp Relative, [00000034], Local, Type: const __int64, nItemCount
// Data           :   ebp Relative, [00000078], Local, Type: struct GameObject *, pObj
// Data           :   ebp Relative, [00000050], Local, Type: struct ArcadiaLock, __lock
// Data           :   ebp Relative, [0000004C], Local, Type: unsigned int, ry2
// Data           :   ebp Relative, [00000040], Local, Type: unsigned int, rx2
// Data           :   ebp Relative, [FFFFFFD0], Local, Type: struct ArcadiaAutoLock, _lock
// Data           :   ebp Relative, [00000060], Local, Type: unsigned int, rx1
// Data           :   ebp Relative, [00000048], Local, Type: unsigned int, ry1
// Data           :   ebp Relative, [00000068], Local, Type: struct StructCreature::iterator, it
// Data           :   ebp Relative, [FFFFFFD0], Local, Type: struct ArcadiaAutoLock, _lock

            Player player = socket.Tag.player;
            if (player == null)
                return;

            uint ct = Globals.GetArTime();

            if (!player.IsItemUseable())
            {
                Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                return;
            }

            Item item = Item.FindItem(_packet.item_handle);

            if (item == null || item.m_Instance.OwnerHandle != player.m_hHandle)
            {
                Messages.SendResult(player, _packet.ID, 1, _packet.item_handle);
                return;
            }

            if (!item.IsInInventory())
                return;

            if (item.m_pItemBase.nType != 3 && !item.IsUsingItem())
            {
                Messages.SendResult(player, _packet.ID, 6, _packet.item_handle);
                return;
            }

            if ( ((item.m_pItemBase.Flag & 0x100) != 0 || !item.IsUsableMoving())
              && player.mv.IsMoving(ct)
              || !item.IsUsableSit() && player.IsSitDown())
            {
                Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                return;
            }

            if (!item.IsUsableInSecroute() && player.IsInSecroute())
            {
                Messages.SendResult(player, _packet.ID, 42, _packet.item_handle);
                return;
            }

            if (!item.IsUsableInSiegeOrRaid() && player.IsInSiegeOrRaidDungeon())
            {
                Messages.SendResult(player, _packet.ID, 44, _packet.item_handle);
                return;
            }

            if (!item.IsUsableInEventmap() && player.IsInEventmap())
            {
                Messages.SendResult(player, _packet.ID, 46, _packet.item_handle);
                return;
            }

            if (HuntaholicManager.Instance.GetHuntaholicID(player.mv) != 0)
            {
                if (!item.IsUsableInHuntaholic())
                {
                    Messages.SendResult(player, _packet.ID, 56, _packet.item_handle);
                    return;
                }
            }
            else
            {
                if (item.IsUsableInOnlyHuntaholic())
                {
                    Messages.SendResult(player, _packet.ID, 59, _packet.item_handle);
                    return;
                }
            }

            nResult = player.IsUseableItem(item, null);
            if (nResult != 0)
            {
                if (nResult == 22)
                    Messages.SendItemCoolTimeInfo(player);
                
                Messages.SendResult(player, _packet.ID, (ushort)nResult, _packet.item_handle);
                return;
            }

            if (player.m_BoothStatus != Player.BoothStatus.IsNotBooth)
            {
                Messages.SendResult(player, _packet.ID, 5, _packet.item_handle);
                return;
            }

            nTargetType = 0;
            nTargetID = 0;
            if ((item.m_pItemBase.Flag & 0x80) != 0)
            {
                pObj = GameObject.raw_get(_packet.target_handle);
                if (pObj != null)
                {
                    cr = pObj as Creature;
                    if (pObj.IsPlayer())
                    {
                        nTargetType = 1;
                        nTargetID = cr.GetSID();
                    }
                    else if (pObj.IsMonster())
                    {
                        nTargetType = 2;
                        nTargetID = cr.GetSID();
                    }
                    else if (pObj.IsSummon())
                    {
                        nTargetType = 3;
                        nTargetID = cr.GetSID();
                    }
                    else if (pObj.IsNPC())
                    {
                        nTargetType = 4;
                        nTargetID = cr.GetSID();
                    }
                    else if (pObj.IsCreature())
                    {
                        nTargetType = 5;
                        nTargetID = cr.GetSID();
                    }
                    else 
                    {
                        nTargetType = 6;
                    }
                }
            }

            if ((item.m_pItemBase.Flag & 0x80) == 0)
            {
                rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                al = new AutoLock(rl.handle);
                nResult = player.UseItem(item, null, _packet.szParameter);
                Messages.SendResult(player,_packet.ID, (ushort) nResult, _packet.item_handle);
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 48));
                if (nResult != 0)
                    return;
            }
            else
            {
                cr = Creature.get(_packet.target_handle) as Creature;

                if (cr == null || cr.m_hHandle == 0)
                {
                    Messages.SendResult(player, _packet.ID, 1, _packet.item_handle);
                    return;
                }
                
                nResult = player.IsUseableItem(item, cr);

                rl = RappelzServer.Instance._LockArea((uint)(player.mv.x / GameContent.g_nRegionSize),
                    (uint)(player.mv.y / GameContent.g_nRegionSize),
                    (uint)(cr.mv.x / GameContent.g_nRegionSize),
                    (uint)(cr.mv.y / GameContent.g_nRegionSize));
    //             while ( 1 )
    //             {
    //                 *(v2 + 88) = g_nRegionSize;
    //                 v20 = *(v2 + 88);
    //                 if ( *(v2 + 96) == (player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 88)) )
    //                 {
    //                     if ( *(v2 + 72) == (player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / v20)
    //                       && *(v2 + 64) == (*(*(v2 + 108) + 108) / v20)
    //                       && *(v2 + 76) == (*(*(v2 + 108) + 112) / v20) )
    //                         break;
    //                 }
    //                 v24 = ArcadiaServer::Instance();
    //                 ArcadiaServer::UnLock(v24, (v2 + 80));
    //                 *(v2 + 88) = g_nRegionSize;
    //                 v25 = *(v2 + 88);
    //                 v26 = player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
    //                 *(v2 + 96) = (player->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 88));
    //                 *(v2 + 72) = (v26 / v25);
    //                 *(v2 + 64) = (*(*(v2 + 108) + 108) / v25);
    //                 v27 = (*(*(v2 + 108) + 112) / v25);
    //                 v28 = *(v2 + 64);
    //                 *(v2 + 76) = v27;
    //                 v29 = *(v2 + 72);
    //                 v30 = *(v2 + 96);
    //                 v31 = ArcadiaServer::Instance();
    //                 *(v2 + 80) = ArcadiaServer::_LockArea(
    //                                  v31,
    //                                  (v2 + 44),
    //                                  v30,
    //                                  v29,
    //                                  v28,
    //                                  v27,
    //                                  "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
    //                                  6184)->handle;
    //             }
    //             ArcadiaAutoLock::ArcadiaAutoLock(
    //                 (v2 - 48),
    //                 (v2 + 80),
    //                 "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
    //                 6187);
                nResult = player.UseItem(item, cr, _packet.szParameter);
                Messages.SendResult(player, _packet.ID, (ushort)nResult, _packet.item_handle);

    //            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 48));

                if (nResult != 0)
                    return;
            }

            ServerLog.Log((ushort)0x966,player.GetAccountID(),player.GetSID(),item.m_Instance.nLevel + 100 * item.m_Instance.nEnhance,
                item.m_Instance.Code,1,item.m_pItemBase.nType == 6 ? item.m_Instance.nCount : item.m_Instance.nCount - 1,
                nTargetID,nTargetID,0,0,item.m_Instance.UID,player.GetAccountName(),player.GetName(),_packet.szParameter,"");

            using(PacketOut pak = new PacketOut(ClientOutPackets.UseItemResult))
            {
                pak.WriteUInt32(_packet.item_handle);
                pak.WriteUInt32(_packet.target_handle);
                player.Connection.SendTCP(pak);
            }
        }

        private void onMix(TCPConnection socket, MixPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;
            RLock rl;
            AutoLock al;
// .text:0046EA11 result          = ArcadiaLock ptr -0B8h
// .text:0046EA11 _lock           = ArcadiaAutoLock ptr -0B4h
            Item[] pSubItem = new Item[9];          // -160 -0A0h
// .text:0046EA11 var_7C          = dword ptr -7Ch
// .text:0046EA11 var_74          = dword ptr -74h
// .text:0046EA11 n3              = qword ptr -70h
// .text:0046EA11 n7              = qword ptr -68h
// .text:0046EA11 n4              = qword ptr -60h
// .text:0046EA11 n1              = qword ptr -58h
// .text:0046EA11 n6              = qword ptr -50h
// .text:0046EA11 n2              = qword ptr -48h
// .text:0046EA11 n5              = qword ptr -40h
// .text:0046EA11 n11             = qword ptr -38h
// .text:0046EA11 n9              = qword ptr -30h
// .text:0046EA11 n10             = qword ptr -28h
// .text:0046EA11 n8              = qword ptr -20h
            ushort[] pCountList = new ushort[9];    // -24 -18h
// .text:0046EA11 var_4           = dword ptr -4
// .text:0046EA11 pClient         = dword ptr  8
// .text:0046EA11 pMsg            = dword ptr  0Ch
            Item pMainItem = null;                  // 84   54h
            int i;                                  // 76   4Ch
// Data           :   ebp Relative, [00000078], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [0000007C], Param, Type: struct TS_CS_MIX *, pMsg
// Data           :   ebp Relative, [00000044], Local, Type: struct TS_CS_MIX::MIX_INFO *, pMixInfo

            rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            al = new AutoLock(rl.handle);

            if (_packet.count > 9)
            {
                if (GameRule.bUseAutoJail)
                {
                    player.AddState(0,State.StateCode.NemesisForAuto,player.m_hHandle,12,Globals.GetArTime(),Globals.GetArTime() + 864000000,false,0,"");
                    player.m_bAutoUsed = true;
                    player.Save(true);
                }

                // TODO: Log and kick off
                return;
            }

            pMainItem = MixManager.check_mixable_item(player, _packet.main_item.handle, 1);
            if (_packet.main_item.handle != 0 && pMainItem == null)
                return;

            MixBase mb = null;
            if (_packet.count != 0)
            {
                i = 0;
                foreach (MixPacketCS.MixInfo mixInfo in _packet.vSubItems)
                {
                    pSubItem[i] = MixManager.check_mixable_item(player, mixInfo.handle, mixInfo.count);
                    if (pSubItem[i] == null)
                        return;
                    pCountList[i] = mixInfo.count;
                    ++i;
                }
            }
            mb = MixManager.GetProperMixInfo(pMainItem, _packet.count, ref pSubItem, ref pCountList);

            if (mb == null)
            {
                Messages.SendResult(player, _packet.ID, 28, 0);
                return;
            }

            switch(mb.type)
            {
                case 0:
                    break;

                case 101:
                case 103:
                    // 101 + 103
                    MixManager.EnhanceItem(mb, player, pMainItem, _packet.count,pSubItem, pCountList);
                    return;

                case 104:
                    // Summon Enhancement
                    MixManager.EnhanceSummon(mb, player, pMainItem, _packet.count, ref pSubItem, ref pCountList);
                    return;

                            // 102, 804, 805
                case 102:
                case 804:
                case 805:
                    MixManager.EnhanceSkillCard(mb,player, pMainItem, _packet.count, ref pSubItem, ref pCountList);
                    return;

//                         // 201,311 + 312
//                         {
//                             pCountList[0] = pCountList;
//                             HIDWORD(n8) = pSubItem;
//                             LODWORD(n8) = _packet->count;
//                             MixManager.MixItemLevel(v14, player, pSubItem, n8, pSubItem, pCountList);
//                             return;
//                         }

//                         // 401 + 402
//                         pCountList[0] = pCountList;
//                         HIDWORD(n8) = pSubItem;
//                         LODWORD(n8) = _packet->count;
//                         MixManager::RecycleItem(v14, player, pSubItem, n8, pSubItem, pCountList);
//                         return;



//                         if (mb.type == 501 )
//                         {
//                             pCountList[0] = pCountList;
//                             HIDWORD(n8) = pSubItem;
//                             LODWORD(n8) = _packet->count;
//                             MixManager::RestoreEnhance(v14, player, pSubItem, n8, pSubItem, pCountList);
//                             return;
//                         }
//                         if (mb.type == 601 )
//                         {
//                             pCountList[0] = pCountList;
//                             HIDWORD(n8) = pSubItem;
//                             LODWORD(n8) = _packet->count;
//                             MixManager::CreateItem(v14, player, pSubItem, n8, pSubItem, pCountList);
//                             return;
//                         }
//                         if (mb.type == 701 )
//                         {
//                             pCountList[0] = pCountList;
//                             HIDWORD(n8) = pSubItem;
//                             LODWORD(n8) = _packet->count;
//                             MixManager::SetElementalEffect(v14, player, pSubItem, n8, pSubItem, pCountList);
//                             return;
//                         }
//                         if ( v15 == 702 )
//                         {
//                             pCountList[0] = pCountList;
//                             HIDWORD(n8) = pSubItem;
//                             LODWORD(n8) = _packet->count;
//                             MixManager::SetElementalEffectParameter(v14, player, pSubItem, n8, pSubItem, pCountList);
//                             return;
//                         }


                default:
                    Globals.Log.Error("Unknown Mix Type: {0}", mb.type);
                    Messages.SendResult(player, _packet.ID, 28, 0);
                    return;
            }
//            ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);


        }

        private void onSoulStoneCraft(TCPConnection socket, SoulStoneCraftPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            long nPrevGold;                      
            int nReplicatedCount;                
            int k;                               
            int nMaxReplicatableCount;           
            int nSocketCount;                    
            long nCraftCost;                     
            int i;                               
            int nEndurance;                      
            Item[] pSoulStoneList = new Item[4]; 
            bool bIsValid = false;

            RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            AutoLock al = new AutoLock(rl.handle);

            try
            {
                if (player.GetLastContactLong("SoulStoneCraft") != 0)
                {
                    Item pItem = Item.FindItem(_packet.craft_item_handle);
                    nPrevGold = player.m_nGold;

                    nSocketCount = pItem.m_pItemBase.nSocketCount;
                    if (pItem.m_Instance.OwnerHandle == player.m_hHandle
                      && pItem.IsInInventory()
                      && nSocketCount > 0
                      && nSocketCount <= 4)
                    {
                        ServerLog.Log((ushort)0x96E, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nCurrentEndurance, pItem.GetMaxEndurance(),
                            pItem.m_Instance.Socket[0], pItem.m_Instance.Socket[1], pItem.m_Instance.Socket[2], pItem.m_Instance.Socket[3], 0, pItem.m_nAccountID,
                            pItem.m_Instance.UID, player.GetAccountName(), player.GetName(), "", "");

                        nMaxReplicatableCount = pItem.m_pItemBase.nSocketCount == 4 ? 2 : 1;
                        nCraftCost = 0;

                        for (i = 0; i < nSocketCount; ++i)
                        {
                            if (_packet.soulstone_handle[i] != 0)
                            {
                                pSoulStoneList[i] = Item.FindItem(_packet.soulstone_handle[i]);
                                if (pSoulStoneList[i] == null
                                  || pSoulStoneList[i].m_Instance.OwnerHandle != player.m_hHandle
                                  || !pSoulStoneList[i].IsInInventory())
                                {
                                    Messages.SendResult(player, _packet.ID, 6, 0);
                                    return;
                                }
                                if (pSoulStoneList[i].m_pItemBase.nType != (int)ItemBase.ItemType.TypeSoulStone
                                    || pSoulStoneList[i].m_pItemBase.nGroup != (int)ItemBase.ItemGroup.SoulStone
                                    || pSoulStoneList[i].m_pItemBase.nClass != ItemBase.ItemClass.ClassSoulStone)
                                {
                                    Messages.SendResult(player, _packet.ID, 5, 0);
                                    return;
                                }

                                nReplicatedCount = 0;
                                k = 0;

                                for (k = 0; k < pItem.m_pItemBase.nSocketCount; ++k)
                                {
                                    if (pItem.m_Instance.Socket[k] != 0 && k != i)
                                    {
                                        ItemBaseServer ibs = Item.GetItemBase(pItem.m_Instance.Socket[k]);
                                        if (ibs.nBaseType[0] == pSoulStoneList[i].m_pItemBase.nBaseType[0]
                                            && ibs.nBaseType[1] == pSoulStoneList[i].m_pItemBase.nBaseType[1]
                                            && ibs.nBaseType[2] == pSoulStoneList[i].m_pItemBase.nBaseType[2]
                                            && ibs.nBaseType[3] == pSoulStoneList[i].m_pItemBase.nBaseType[3]
                                            && ibs.fBaseVar1[0] == pSoulStoneList[i].m_pItemBase.fBaseVar1[0]
                                            && ibs.fBaseVar1[1] == pSoulStoneList[i].m_pItemBase.fBaseVar1[1]
                                            && ibs.fBaseVar1[2] == pSoulStoneList[i].m_pItemBase.fBaseVar1[2]
                                            && ibs.fBaseVar1[3] == pSoulStoneList[i].m_pItemBase.fBaseVar1[3]
                                            && ibs.nOptType[0] == pSoulStoneList[i].m_pItemBase.nOptType[0]
                                            && ibs.nOptType[1] == pSoulStoneList[i].m_pItemBase.nOptType[1]
                                            && ibs.nOptType[2] == pSoulStoneList[i].m_pItemBase.nOptType[2]
                                            && ibs.nOptType[3] == pSoulStoneList[i].m_pItemBase.nOptType[3]
                                            && ibs.fOptVar1[0] == pSoulStoneList[i].m_pItemBase.fOptVar1[0]
                                            && ibs.fOptVar1[1] == pSoulStoneList[i].m_pItemBase.fOptVar1[1]
                                            && ibs.fOptVar1[2] == pSoulStoneList[i].m_pItemBase.fOptVar1[2]
                                            && ibs.fOptVar1[3] == pSoulStoneList[i].m_pItemBase.fOptVar1[3])
                                        {
                                            nReplicatedCount++;
                                            if (nReplicatedCount >= nMaxReplicatableCount)
                                            {
                                                Messages.SendResult(player, _packet.ID, 9, 0);
                                                return;
                                            }
                                        }
                                    }
                                }
                                nCraftCost += pSoulStoneList[i].m_pItemBase.nPrice / 10;
                                bIsValid = true;
                            }
                        }

                        if (!bIsValid)
                        {
                            ServerLog.Log((ushort)0x96F, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nLevel + 100 * pItem.m_Instance.nEnhance,
                                pItem.m_Instance.Code, pSoulStoneList[0] == null ? 0 : pSoulStoneList[0].m_Instance.Code,
                                pSoulStoneList[1] == null ? 0 : pSoulStoneList[1].m_Instance.Code, pSoulStoneList[2] == null ? 0 : pSoulStoneList[2].m_Instance.Code,
                                pSoulStoneList[3] == null ? 0 : pSoulStoneList[3].m_Instance.Code, player.m_nGold, player.m_nGold, pItem.m_Instance.UID,
                                player.GetAccountName(), player.GetName(), "INVALID_CRAFT_INFO", "FAIL");
                            return;
                        }
                        if (nPrevGold < nCraftCost || player.ChangeGold(nPrevGold - nCraftCost) != 0)
                        {
                            Messages.SendResult(player, _packet.ID, 10, 0);
                            ServerLog.Log((ushort)0x96F, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nLevel + 100 * pItem.m_Instance.nEnhance,
                                pItem.m_Instance.Code, pSoulStoneList[0] == null ? 0 : pSoulStoneList[0].m_Instance.Code,
                                pSoulStoneList[1] == null ? 0 : pSoulStoneList[1].m_Instance.Code, pSoulStoneList[2] == null ? 0 : pSoulStoneList[2].m_Instance.Code,
                                pSoulStoneList[3] == null ? 0 : pSoulStoneList[3].m_Instance.Code, nPrevGold, player.m_nGold, pItem.m_Instance.UID,
                                player.GetAccountName(), player.GetName(), "NOT_ENOUGH_MONEY", "FAIL");
                            return;
                        }
                        ServerLog.Log((ushort)0x96F, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nLevel + 100 * pItem.m_Instance.nEnhance,
                            pItem.m_Instance.Code, pSoulStoneList[0] == null ? 0 : pSoulStoneList[0].m_Instance.Code,
                            pSoulStoneList[1] == null ? 0 : pSoulStoneList[1].m_Instance.Code, pSoulStoneList[2] == null ? 0 : pSoulStoneList[2].m_Instance.Code,
                            pSoulStoneList[3] == null ? 0 : pSoulStoneList[3].m_Instance.Code, nPrevGold, player.m_nGold, pItem.m_Instance.UID,
                            player.GetAccountName(), player.GetName(), "", "SUCS");

                        nEndurance = 0;
                        for (i = 0; i < 4; ++i)
                        {
                            if (pItem.m_Instance.Socket[i] != 0 || pSoulStoneList[i] != null)
                            {
                                if (pSoulStoneList[i] != null)
                                {
                                    nEndurance += pSoulStoneList[i].m_Instance.nCurrentEndurance;
                                    pItem.m_Instance.Socket[i] = pSoulStoneList[i].m_Instance.Code;
                                    player.EraseItem(pSoulStoneList[i], 1);
                                }
                                else
                                {
                                    nEndurance += pItem.m_Instance.nCurrentEndurance;
                                }
                            }
                        }

                        player.Save(false);
                        pItem.SetCurrentEndurance(nEndurance);
                        pItem.m_bIsNeedUpdateToDB = true;
                        pItem.DBQuery(new DB_UpdateItem(pItem));
                        ServerLog.Log((ushort)0x96E, player.GetAccountID(), player.GetSID(), pItem.m_Instance.nCurrentEndurance, pItem.GetMaxEndurance(),
                            pItem.m_Instance.Socket[0], pItem.m_Instance.Socket[1], pItem.m_Instance.Socket[2], pItem.m_Instance.Socket[3], 0, pItem.m_nAccountID,
                            pItem.m_Instance.UID, player.GetAccountName(), player.GetName(), "", "");
                        player.SetLastContact("SoulStoneCraft", 0);
                        Messages.SendItemMessage(player, pItem);
                        player.CalculateStat();
                        Messages.SendResult(player, _packet.ID, 0, 0);
                    }
                    else
                    {
                        Messages.SendResult(player, _packet.ID, 6, 0);
                    }
                }
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
//                ArcadiaAutoLock._ArcadiaAutoLock((v2 - 40));
            }

        }

        private void onRepairSoulStone(TCPConnection socket, RepairSoulStonePacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            int i;                          // 68   44h
            List<RappelzPair<Item,int>> vItemList = new List<RappelzPair<Item,int>>();  // 80   50h
            int nTotalRepair;               // 104  68h
            int nCostChaos;                 // 108  6Ch
// .text:0047C8AB pClient         = dword ptr  120  78h
// .text:0047C8AB pMsg            = dword ptr  124  7Ch
// .text:0047C8AB it              = std._Vector_iterator<std.pair<StructItem *,int>,std.allocator<std.pair<StructItem *,int> > > ptr  100 60h

            RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
            AutoLock al = new AutoLock(rl.handle);

            try
            {
                if (player.GetLastContactLong("RepairSoulStone") == 0)
                    return;

                player.SetLastContact("RepairSoulStone", 0);

                nTotalRepair = 0;
                //*(v2 + 108) = v7 + 7; item_handle it
                for(i = 0; i < 6; ++i)
                {
                    if (_packet.item_handle[i] != 0)
                    {
                        Item pItem = Item.FindItem(_packet.item_handle[i]);

                        if (pItem == null
                          || pItem.m_Instance.OwnerHandle != player.m_hHandle
                          || !pItem.IsInInventory())
                        {
                            Messages.SendResult(player, _packet.ID, 1, 0);
                            return;
                        }

                        if (pItem.GetUsingSocketCount() == 0 || pItem.GetMaxEndurance() == pItem.m_Instance.nCurrentEndurance)
                        {
                            Messages.SendResult(player, _packet.ID, 5, 0);
                            return;
                        }
                        nTotalRepair += pItem.m_Instance.nCurrentEndurance;
                        vItemList.Add(new RappelzPair<Item,int>(pItem,pItem.m_Instance.nCurrentEndurance));
                    }
                }

                nCostChaos = (int)((double)nTotalRepair * 1.2 + 0.9);
                if (vItemList.Count == 0)
                {
                    Messages.SendResult(player, _packet.ID, 5, 0);
                    return;
                }
                
                if (player.m_nChaos >= nCostChaos)
                {
                    foreach (RappelzPair<Item,int> rp in vItemList)
                    {
                        int oldChaos = player.m_nChaos;
                        rp.First.SetCurrentEndurance(rp.First.m_Instance.nCurrentEndurance + rp.Second);
                        Messages.SendItemMessage(player, rp.First);
                        ServerLog.Log((ushort)0x970,player.GetAccountID(),player.GetSID(),oldChaos,player.m_nChaos,rp.First.m_Instance.nCurrentEndurance,
                            rp.First.m_Instance.nCurrentEndurance,rp.First.GetMaxEndurance(),0,0,0,rp.First.m_Instance.UID,player.GetAccountName(),player.GetName(),"","");
                    }
                }
                else
                {
//                     if ( v12 > 1 || (*(v2 + 100) = player.m_nChaos, v15 = , (nTotalRepair = (player.m_nChaos / 1.2)) == 0) )
//                     {
//                         Messages.SendResult(player, _packet.ID, 10, 0);
//                         return;
//                     }
/*
                    std._Vector_const_iterator<StateDamage_std.allocator<StateDamage>>._Vector_const_iterator<StateDamage_std.allocator<StateDamage>>(
                        (v2 - 28),
                        *(v2 + 84),
                        (v2 + 80));
                    v16 = std._Vector_const_iterator<PartyManager.PartyInfo___std.allocator<PartyManager.PartyInfo__>>.operator_((v2 - 28));
                    v17 = v16.end.x;
                    v18 = *(LODWORD(v16.end.x) + 248);
                    v19 = v18 + 100000 * nTotalRepair;
                    *(v2 + 100) = v18;
                    StructItem.SetCurrentEndurance(LODWORD(v17), v19);
                    SendItemMessage(player, LODWORD(v17));
                    nCostChaos = player.m_nChaos;
                    *(v2 + 56) = *(LODWORD(v17) + 200);
                    *(v2 + 60) = *(LODWORD(v17) + 204);
                    *(v2 + 72) = 0;
                    *(v2 + 76) = 0;
                    *(v2 + 64) = 0;
                    *(v2 + 68) = 0;
                    *(v2 - 20) = 0;
                    *(v2 - 16) = 0;
                    LODWORD(v20) = StructItem.GetMaxEndurance(LODWORD(v17));
                    v21 = player.m_nChaos;
                    v20 = v20;
                    *(v2 + 32) = v20;
                    LODWORD(v20) = *(LODWORD(v17) + 248);
                    *(v2 + 36) = HIDWORD(v20);
                    v20 = v20;
                    *(v2 + 40) = v20;
                    LODWORD(v20) = *(v2 + 100);
                    *(v2 + 44) = HIDWORD(v20);
                    v20 = v20;
                    *(v2 + 24) = v20;
                    LODWORD(v20) = v21 - nCostChaos;
                    *(v2 + 28) = HIDWORD(v20);
                    *(v2 + 16) = v20;
                    *(v2 + 8) = v21;
                    LODWORD(v20) = player.....vfptr;
                    *(v2 + 12) = v21 >> 32;
                    *v2 = (*(v20 + 64))(player);
                    v22 = StructPlayer.GetAccountID(player);
                    *(v2 + 48) = v22;
                    LODWORD(v22) = player.....vfptr;
                    *(v2 + 52) = HIDWORD(v22);
                    v23 = (*(v22 + 60))(player);
                    v24 = StructPlayer.GetAccountName(player);
                    LOG.Log11N4S(
                        0x970u,
                        (v2 + 48),
                        v2,
                        (v2 + 8),
                        (v2 + 16),
                        (v2 + 24),
                        (v2 + 40),
                        (v2 + 32),
                        (v2 - 20),
                        (v2 + 64),
                        (v2 + 72),
                        (v2 + 56),
                        v24,
                        -1,
                        v23,
                        -1,
                        &unk_5F42BB,
                        0,
                        &unk_5F42BB,
                        0);
*/
                }

                player.AddChaos(-nCostChaos);
                player.CalculateStat();
                player.Save(true);
//                 if ( !*(v2 + 84) || (*(v2 + 88) - *(v2 + 84)) >> 3 != 1 || (v34 = nCostChaos, nCostChaos >= nTotalRepair) )
//                     v34 = 0;
//                 v36 = v34;
                Messages.SendResult(player, _packet.ID, 0, 0);
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
//            ArcadiaAutoLock._ArcadiaAutoLock((v2 - 48));

            }

        }

        private void onEquipSummon(TCPConnection socket, EquipSummonPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

//.text:00479729 _lock           = ArcadiaAutoLock ptr -64h
            int i;                                      // -64  -40h
            int nCreatureControlLevel;                  // -52  -34h
            int x;                                      // -48  -30h
            string strFirstSummonHandler;               // -44  -2Ch
//.text:00479729 pClient         = dword ptr  8
//.text:00479729 pMsg            = dword ptr  0Ch
            RLock rl;
            AutoLock al;
            Item pItem;
            Summon summon;


            if (player.IsItemUseable())
            {
                nCreatureControlLevel = player.GetCurrentPassiveSkillLevel((int)SkillBase.SkillId.CreatureControl);
                if (nCreatureControlLevel > 6)
                    nCreatureControlLevel = 6;

                rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                al = new AutoLock(rl.handle);
                i = 0;
                if (nCreatureControlLevel > 0)
                {
                    for(i = 0; i < 6; ++i)
                    {
                        bool bFound = false;
                        pItem = null;
                        if (_packet.card_handle[i] != 0)
                        {
                            pItem = Item.FindItem(_packet.card_handle[i]);

                            if (pItem != null)
                            {
                                if (pItem.m_pItemBase.nGroup != 13
                                  || player.m_hHandle != pItem.m_Instance.OwnerHandle
                                  || (pItem.m_Instance.Flag & (uint)ItemInstance.FlagBits.Summon) == 0
                                  || !pItem.IsInInventory())
                                    continue;
                            }
                        }
                        for (x = 0; x < 6; ++x)
                        {
                            if (pItem != null)
                            {
                                if (player.m_aBeltSlotCard[x] != null && player.m_aBeltSlotCard[x].m_hHandle == pItem.m_hHandle)
                                    bFound = true;
                            }
                        }

                        if (bFound)
                            continue;

                        if (player.m_aBindSummonCard[i] != null)
                        {
                            if (pItem == null || player.m_aBindSummonCard[i].m_hHandle != pItem.m_hHandle)
                            {
                                summon = player.m_aBindSummonCard[i].m_pSummon;
                                if (_packet.card_handle[i] == 0)
                                    player.m_aBindSummonCard[i] = null;
                                if (summon != null && !summon.bIsInWorld)
                                {
                                    for (x = 0; x < 24; ++x)
                                    {
                                        if (summon.GetWornItem((ItemBase.ItemWearType)x) != null)
                                            summon.Putoff((ItemBase.ItemWearType)x);
                                    }
                                }
                            }
                        }


                        if (pItem != null)
                        {
                            if ((pItem.m_Instance.Flag & 0x80000000) != 0)
                            {
                                summon = pItem.m_pSummon;
                                if (summon == null)
                                {
                                    summon = MemoryPool.AllocNewSummon(player, pItem);
                                    summon.m_StatusFlag |= Creature.StatusFlags.LoginComplete;
                                    player.AddSummon(summon, true);
                                    Messages.SendItemMessage(player, pItem);

                                    player.DBQuery(new DB_InsertSummon(player,summon.GetSID(),0,player.m_nUID,summon.GetSummonCode(),
                                            summon.m_item.m_Instance.UID, summon.GetName(), summon.m_nSP, summon.m_nHP, summon.m_fMP));

                                    strFirstSummonHandler = String.Format("on_first_summon( {0}, {1} )", summon.GetSummonCode(), summon.GetHandle());
                                    LuaVM.Instance.RunString(player, strFirstSummonHandler);
                                    summon.CalculateStat();
                                }
                                summon.m_cSlotIndex = (byte)i;
                                summon.CalculateStat();
                            }
                            player.m_aBindSummonCard[i] = pItem;
                        }

                    }
                }
                if (nCreatureControlLevel > 1)
                {
                    for (i = 0; i < 6; ++i)
                    {
                        if(player.m_aBindSummonCard[i] == null)
                        {
                            for(x = i+1; x < 6;++x)
                            {
                                if(player.m_aBindSummonCard[x] != null)
                                {
                                    player.m_aBindSummonCard[i] = player.m_aBindSummonCard[x];
                                    player.m_aBindSummonCard[x] = null;
                                }
                            }
                        }
                    }
                }
                Messages.SendCreatureEquipMessage(player, false);
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 100));
            }
        }


        private void onGetSummonSetupInfo(TCPConnection socket, GetSummonSetupInfoPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            RLock rl = RappelzServer.Instance._LockObject(player);
            AutoLock al = new AutoLock(rl.handle);
            Messages.SendCreatureEquipMessage(player, _packet.show_dialog);
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 36));
        }

        private void onSetPetName(TCPConnection socket, SetPetNamePacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            RLock rl;
            AutoLock al;

            try
            {
                if (_packet.handle != 0)
                {
                    rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                    al = new AutoLock(rl.handle);
                    Pet pet = Pet.get(_packet.handle) as Pet;

                    if (pet == null
                      || pet.bIsInWorld
                      || (pet.m_ContentInfo.attribute_flag & 1) == 0
                      || pet.m_bNameChanged
                      || pet.m_item == null
                      || pet.m_item.m_Instance.OwnerHandle != player.m_hHandle
                      || pet.m_master.m_hHandle != player.m_hHandle)
                        return;

                    ushort res = pet.ChangeName(_packet.name);

                    switch(res)
                    {
                        case 6:  // bad words
                        case 16: // too long
                            Messages.PrintfChatMessage(false, 20, "@SYSTEM", player, "@1106");
                            break;
                        case 9: // same name
                            Messages.PrintfChatMessage(false, 20, "@SYSTEM", player, "@118");
                            break;
                        case 17: // too short
                            Messages.PrintfChatMessage(false, 20, "@SYSTEM", player, "@1105");
                            break;
                    }

                    Messages.SendResult(player, _packet.ID, res, _packet.handle);
                }
            }
            catch (System.Exception ex)
            {
            	
            }
            finally
            {
//                            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 44));
            }

        }



        private void onSkill(TCPConnection socket, SkillPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

// .text:004764B0 _lock           = ArcadiaAutoLock ptr -64h
            ArPosition targetPos = new ArPosition();// 64 40h
// .text:004764B0 __lock          = ArcadiaLock ptr  50h
// .text:004764B0 rx              = dword ptr  54h
// .text:004764B0 _ry             = dword ptr  5Ch
            SkillBase pBase;                        // 96 60h
            Creature pCaster = null;                // 100 64h
            GameObject pTarget = null;
            float tx = 0;
            float ty = 0;
// .text:004764B0 ry              = dword ptr  6Ch
// .text:004764B0 pClient         = dword ptr  78h
// .text:004764B0 pMsg            = dword ptr  7Ch
// 
// Data           :   ebp Relative, [00000078], Param, Type: struct StructPlayer *, pClient
// Data           :   ebp Relative, [0000007C], Param, Type: struct TS_CS_SKILL *, pMsg
// Data           :   ebp Relative, [0000006C], Local, Type: unsigned int, ry
// Data           :   ebp Relative, [00000064], Local, Type: unsigned int, _rx
// Data           :   ebp Relative, [0000005C], Local, Type: unsigned int, _ry
// Data           :   ebp Relative, [00000050], Local, Type: struct ArcadiaLock, __lock
// Data           :   ebp Relative, [FFFFFF9C], Local, Type: struct ArcadiaAutoLock, _lock
// Data           :   ebp Relative, [00000060], Local, Type: struct SkillBase *, pBase
// Data           :   ebp Relative, [00000054], Local, Type: unsigned int, rx
// Data           :   ebp Relative, [00000064], Local, Type: struct StructCreature *, pCaster
// Data           :   ebp Relative, [00000058], Local, Type: struct GameObject::iterator, it
// Data           :   ebp Relative, [00000040], Local, Type: struct ArPosition, targetPos


            if (player.m_nHP != 0)
            {
                targetPos.x = _packet.x;
                targetPos.y = _packet.y;
                targetPos.z = _packet.z;

                pCaster = player;

                if (_packet.caster != player.m_hHandle)
                    pCaster = player.GetSummon(_packet.caster) as Creature;

                if (pCaster == null || !pCaster.bIsInWorld )
                {
                    targetPos.x = _packet.x;
                    targetPos.y = _packet.y;
                    targetPos.z = _packet.z;
                    Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,1);
                    return;
                }
                pBase = GameContent.GetSkillBase(_packet.skill_id);
                if (pBase == null || pBase.is_valid == 0 || pBase.is_valid == 2)
                {
                    targetPos.x = _packet.x;
                    targetPos.y = _packet.y;
                    targetPos.z = _packet.z;
                    Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,6);
                    return;
                }
                if (pBase.is_spell_act == 0)
                {
                    if (!pCaster.IsSkillCastable())
                    {
                        targetPos.x = _packet.x;
                        targetPos.y = _packet.y;
                        targetPos.z = _packet.z;
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,5);
                        return;
                    }
                }
                else 
                {
                    if (!pCaster.IsMagicCastable())
                    {
                        targetPos.x = _packet.x;
                        targetPos.y = _packet.y;
                        targetPos.z = _packet.z;
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,5);
                        return;
                    }
                }

                tx = (_packet.x / GameContent.g_nRegionSize);
                ty = (_packet.y / GameContent.g_nRegionSize);
                if (_packet.target != 0)
                {
                    pTarget =  GameObject.get(_packet.target);
                    if (pTarget == null)
                    {
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,1);
                        return;
                    }
                    if (pTarget.IsCreature())
                    {
                        tx = (pTarget.mv.x / GameContent.g_nRegionSize);
                        ty = (pTarget.mv.y / GameContent.g_nRegionSize);
                    }
                    else
                    {
                        tx = (pCaster.mv.x / GameContent.g_nRegionSize);
                        ty = (pCaster.mv.y / GameContent.g_nRegionSize);
                    }
                    if (pTarget.IsCreature() && !GameContent.isValidTarget(player, pTarget))
                    {
                        Messages.SendLeaveMsg(player, pTarget);
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,1);
                        return;
                    }
                }

                RLock rl = RappelzServer.Instance._LockArea((uint)(pCaster.mv.x / GameContent.g_nRegionSize),(uint)(pCaster.mv.y / GameContent.g_nRegionSize),(uint)(tx),(uint)(ty));
                AutoLock al = new AutoLock(rl.handle);
//                 while ( 1 )
//                 {
//                     *(v2 + 104) = g_nRegionSize;
//                     if ( *(v2 + 100) == (*v21 / *(v2 + 104)) )
//                     {
//                         if ( *(v2 + 92) == (pCaster.baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / *(v2 + 104)) )
//                             break;
//                     }
//                     v27 = ArcadiaServer::Instance();
//                     ArcadiaServer::UnLock(v27, (v2 + 80));
//                     *(v2 + 104) = g_nRegionSize;
//                     v28 = pCaster.baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / *(v2 + 104);
//                     *(v2 + 100) = (*v21 / *(v2 + 104));
//                     v29 = *(v2 + 108);
//                     *(v2 + 92) = v28;
//                     v30 = *(v2 + 84);
//                     v31 = *(v2 + 100);
//                     v32 = ArcadiaServer::Instance();
//                     *(v2 + 80) = ArcadiaServer::_LockArea(
//                                      v32,
//                                      (v2 - 64),
//                                      v31,
//                                      v28,
//                                      v30,
//                                      v29,
//                                      "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                      5986).handle;
//                 }
//                 ArcadiaAutoLock::ArcadiaAutoLock(
//                     (v2 - 100),
//                     (v2 + 80),
//                     "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                     5990);
                uint ct = Globals.GetArTime();
                if (pCaster.mv.IsMoving(ct))
                {
                    Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,5);
                    return;
                }

                if (pBase.is_spell_act == 0)
                {
                    if ( !pCaster.IsSkillCastable())
                    {
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,5);
                        return;
                    }
                }
                else
                {
                    if (!pCaster.IsMagicCastable())
                    {
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,5);
                        return;
                    }
                }

                Skill skill = pCaster.GetSkill(_packet.skill_id);
                if (skill != null && skill.m_nSkillUID != -1)
                {
                    if (_packet.skill_level > skill.m_nSkillLevel + skill.m_nSkillLevelAdd)
                        _packet.skill_level = (byte)(skill.m_nSkillLevel + skill.m_nSkillLevelAdd);
                    int res = pCaster.CastSkill(_packet.skill_id,_packet.skill_level,_packet.target,targetPos, pCaster.m_layer, false);
                    if (res != 0)
                        Skill.SendSkillCastFailMessage(player,_packet.caster,_packet.target,_packet.skill_id,_packet.skill_level,targetPos,res);
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 100));
            }
        }

        private void onLearnSkill(TCPConnection socket, LearnSkillPacketCS _packet)
        {
//.text:0046EDF6 _lock           = ArcadiaAutoLock ptr -34h
//.text:0046EDF6 it              = StructCreature::iterator ptr -20h
            int nJobId;                 // -16 -10h
            //.text:0046EDF6 pClient         = dword ptr  4
            Creature pCreature;         // 8  8
            //.text:0046EDF6 pMsg            = dword ptr  0Ch
            ushort result = 0;
            int value = 0;
            RLock rl;
            AutoLock al;


            Player player = socket.Tag.player;
            if(player == null)
                return;

            Creature target = player;

            if (player.m_hHandle != _packet.target)
            {
                Summon summon = Creature.get(_packet.target) as Summon;
                if (summon == null || !summon.IsSummon() || !ReferenceEquals(summon.m_master, player))
                {
                    Messages.SendResult(player, _packet.ID, 6, 0);
                    return;
                }
                target = summon;
            }
            int currentLevel = target.GetBaseSkillLevel(_packet.skill_id)+1;
            if (_packet.skill_level == currentLevel)
            {
                result = (ushort)GameContent.IsLearnableSkill(target, _packet.skill_id, currentLevel, out nJobId);
                if (result == 0)
                {
                    rl = RappelzServer.Instance._LockObjectWithVisibleRange(target);
                    al = new AutoLock(rl.handle);

                    target.RegisterSkill(_packet.skill_id, _packet.skill_level, 0, nJobId);
                    player.Save(true);
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 52));
                    value = _packet.skill_id;
                    result = 0;
                }
                Messages.SendResult(player, _packet.ID, result, value);
            }
        }


        private void onJobLevelUp(TCPConnection socket, JobLevelUpPacketCS _packet)
        {
            //.text:0046EF2A _lock           = ArcadiaAutoLock ptr -88h
            //.text:0046EF2A it              = StructCreature::iterator ptr -24h
            int jp;//              = dword ptr -16 -10h
            RLock rl;
            AutoLock al;
// .text:0046EF2A pClient         = dword ptr  8
// .text:0046EF2A pMsg            = dword ptr  0Ch
// Data           :   ebp Relative, [FFFFFF78], Local, Type: struct ArcadiaAutoLock, _lock
// Data           :   ebp Relative, [FFFFFFF0], Local, Type: int, jp
// Data           :   ebp Relative, [FFFFFFDC], Local, Type: struct StructCreature::iterator, it


            Player client = socket.Tag.player;
            if (client == null)
                return;

            Creature cr = Creature.get(_packet.target) as Creature;
            Player player = cr as Player;
            Summon summon = cr as Summon;

            if (cr == null)
            {
                Messages.SendResult(client, _packet.ID, 1, (int)_packet.target);
                return;
            }
            if (cr.IsPlayer() && !ReferenceEquals(client,cr))
            {
                Messages.SendResult(client, _packet.ID, 6, (int)_packet.target);
                return;
            }
            if (cr.IsSummon() && !ReferenceEquals(summon.m_master, client))
            {
                Messages.SendResult(client, _packet.ID, 6, (int)_packet.target);
                return;
            }

            jp = GameContent.GetNeedJpForJobLevelUp(cr.GetJobLevel(), cr.GetJobDepth());
            if (cr.GetJobPoint() < jp)
            {
                Messages.SendResult(client, _packet.ID, 12, (int)_packet.target);
                return;
            }
            if (jp == 0 )
            {
                Messages.SendResult(client, _packet.ID, 16, (int)_packet.target);
                return;
            }

            rl = RappelzServer.Instance._LockObjectWithVisibleRange(cr);
            al = new AutoLock(rl.handle);

            cr.SetJP(cr.GetJobPoint() - jp);
            cr.SetJobLevel(cr.GetJobLevel()+1);
            cr.CalculateStat();
            if (cr.IsPlayer())
            {
                player.Save(true);
                ServerLog.Log((ushort)0x8FF,player.GetAccountID(),player.GetSID(),0,player.GetJobId(),player.GetJobLevel(),jp,player.GetJobPoint(),0,
                    0,0,0,player.GetAccountName(),player.GetName(),"","");
                LuaVM.Instance.RunString(player, "on_player_level_joblevel_guide()");
            }
            else
            {
                if (cr.IsSummon())
                {
                    player = summon.m_master;
                    ServerLog.Log((ushort)0x8FF,player.GetAccountID(),player.GetSID(),summon.GetSID(),summon.GetJobId(),summon.GetJobLevel(),
                        jp,summon.GetJobPoint(),0,0,0,0,player.GetAccountName(),player.GetName(),"","");
                }
            }
            client.Save(true);

            Messages.SendPropertyMessage(client, cr.m_hHandle, "job_level", cr.GetJobLevel());
            Messages.SendResult(client, _packet.ID, 0, (int) _packet.target);

//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 136));
        }


        private void onUpdate(TCPConnection socket, UpdatePacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;
            Creature creature = (Creature) player;

            if (_packet.handle != player.GetHandle())
                creature = socket.Tag.player.GetSummon(_packet.handle);
            if (creature != null)
            {
                if (creature.IsPlayer())
                {
                    if (player.IsPendWarp())
                    {
                        RappelzServer.Instance.SetObjectPriority(creature, SchedulerObject.Priority.Highest);
                    }
                }
//                    v8 = RappelzServer.Instance._LockObjectWithVisibleRange((ArcadiaLock *)(v2 + 8), creature);
//                     ArcadiaAutoLock::ArcadiaAutoLock((ArcadiaAutoLock *)(v2 - 32),v8);
                creature.OnUpdate();
//                ArcadiaAutoLock::_ArcadiaAutoLock((ArcadiaAutoLock *)v10);
            }
        }

        private void onSetProperty(TCPConnection socket, SetPropertyPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (_packet.Length <= 4452)
            {
                RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                AutoLock al = new AutoLock(rl.handle);
                if(_packet.name == "client_info")
                {
                    GameDBManager.Instance.Push(new DB_UpdateClientInfo(player.m_nUID, _packet.value));
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 60));
            }
            else
            {
                Globals.Log.Error("onSetProperty() : too big property!");
            }
        }

        private void onTargeting(TCPConnection socket, TargetingPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            if (player.m_hTarget != 0)
            {
                Creature c = Creature.get(player.m_hTarget) as Creature;
                if (c != null)
                {
                    RLock rl1 = RappelzServer.Instance._LockObject(c);
                    AutoLock al1 = new AutoLock(rl1.handle);
                    c.RemoveAimer(player.m_hHandle);
//                    ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 80));
                }
                player.SetTarget(0);
            }

            if (_packet.target != 0)
            {
                if (_packet.target != player.m_hHandle)
                {
                    Creature creature = Creature.get(_packet.target) as Creature;
                    if (creature != null)
                    {
                        RLock rl2 = RappelzServer.Instance._LockObject(creature);
                        AutoLock al2 = new AutoLock(rl2.handle);
                        creature.AddAimer(player.m_hHandle);
                        player.SetTarget(creature.m_hHandle);
                        //ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 80));

                        RLock rl3 = RappelzServer.Instance._LockArea((uint)(player.mv.x / GameContent.g_nRegionSize),(uint)(player.mv.y / GameContent.g_nRegionSize),
                            (uint)(creature.mv.x / GameContent.g_nRegionSize), (uint)(creature.mv.y / GameContent.g_nRegionSize));
//                         while ( 1 )
//                         {
//                             *(v2 + 8) = g_nRegionSize;
//                             v28 = *(v2 + 8);
//                             if ( *(v2 - 20) == (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 8)) )
//                             {
//                                 if ( *(v2 - 16) == (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y / v28)
//                                   && *(v2 + 12) == (*(v12 + 108) / v28)
//                                   && *(v2 - 28) == (*(v12 + 112) / v28) )
//                                     break;
//                             }
//                             v29 = ArcadiaServer::Instance();
//                             ArcadiaServer::UnLock(v29, (v2 - 24));
//                             *(v2 + 8) = g_nRegionSize;
//                             v30 = *(v2 + 8);
//                             v31 = v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.y;
//                             *(v2 - 20) = (v3->baseclass_0.baseclass_0.baseclass_0.mv.baseclass_0.x / *(v2 + 8));
//                             v32 = (v31 / v30);
//                             v33 = *(v12 + 108);
//                             *(v2 - 16) = v32;
//                             v34 = (v33 / v30);
//                             v35 = *(v12 + 112) / v30;
//                             *(v2 + 12) = v34;
//                             v36 = *(v2 + 12);
//                             *(v2 - 28) = v35;
//                             v37 = *(v2 - 16);
//                             v38 = *(v2 - 20);
//                             v39 = ArcadiaServer::Instance();
//                             *(v2 - 24) = ArcadiaServer::_LockArea(
//                                              v39,
//                                              (v2 - 32),
//                                              v38,
//                                              v37,
//                                              v36,
//                                              v35,
//                                              "D:\\alienbrainWork\\Source Code\\@Rappelz\\Server\\GameServer_For_Update\\090721_GameServer\\Game\\Message\\GameMessage.cpp",
//                                              6793)->handle;
//                         }
                        AutoLock al3 = new AutoLock(rl3.handle);

                        if ( !GameContent.isValidTarget(player, creature))
                            Messages.SendLeaveMsg(player, creature);
//                        ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 60));
                    }
                }
            }
        }


        private void onResurrection(TCPConnection socket, ResurrectionPacketCS _packet)
        {
            Player player = socket.Tag.player;
            if (player == null)
                return;

            int nHuntaholicID;// Data           :   ebp Relative, [00000048], Local, Type: int, 
            Creature pTarget;// Data           :   ebp Relative, [00000040], Local, Type: struct StructCreature *, 
            int nHPInc;// Data           :   ebp Relative, [00000048], Local, Type: int, 
// Data           :   ebp Relative, [0000004C], Local, Type: int, nHPInc
            ArPosition posLobby;// Data           :   ebp Relative, [FFFFFEFC], Local, Type: struct ArPosition, 
// Data           :   constant 0x2, Constant, Type: enum onResurrection::__l36::_REVIVE_TYPE, REVIVE_COMPETE
// Typedef        :   onResurrection::__l36::_REVIVE_TYPE, Type: enum onResurrection::__l36::_REVIVE_TYPE
// Data           :   constant 0x3, Constant, Type: enum onResurrection::__l36::_REVIVE_TYPE, REVIVE_DUNGEON_SIEGE
            int eReviveType;// Data           :   ebp Relative, [00000048], Local, Type: enum onResurrection::__l36::_REVIVE_TYPE, 
// Data           :   constant 0x0, Constant, Type: enum onResurrection::__l36::_REVIVE_TYPE, REVIVE_NORMAL
            string strReviveHandler;// Data           :   ebp Relative, [00000050], Local, Type: class std::basic_string<char,std::char_traits<char>,std::allocator<char> >, 
            RLock rl;
            AutoLock al;
            pTarget = player;

// Data           :     constant 0x0, Constant, Type: int, RESURRECT_TYPE_NORMAL
// Data           :     constant 0x1, Constant, Type: int, RESURRECT_TYPE_BY_STATE
// Data           :     constant 0x2, Constant, Type: int, RESURRECT_TYPE_BY_POTION
// Data           :     constant 0x3, Constant, Type: int, RESURRECT_TYPE_BY_COMPETE

            if (_packet.type == 1) // RESURRECT_TYPE_BY_STATE
            {
                rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                al = new AutoLock(rl.handle);

                if (player.m_hHandle == _packet.handle)
                {
                    pTarget = player;
                }
                else
                {
                    pTarget = player.GetSummon(_packet.handle) as Creature;
                    if (pTarget == null)
                    {
//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
                    }
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock(&v52);
                rl = RappelzServer.Instance._LockObjectWithVisibleRange(pTarget);
                al = new AutoLock(rl.handle);

                pTarget.ResurrectByState();

//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
            }
            if (_packet.type == 2) // RESURRECT_TYPE_BY_POTION
            {
                rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                al = new AutoLock(rl.handle);

                if (player.m_nHP != 0)
                {
//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
                }

                if (player.ResurrectByPotion())
                {
//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
                }
                
//                ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
            }
            else
            {
                if (_packet.type == 3) // RESURRECT_TYPE_BY_COMPETE
                {
                    rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                    al = new AutoLock(rl.handle);

                    if (player.m_nHP == 0 && (player.m_StatusFlag & Creature.StatusFlags.CompeteDead) != 0)
                        player.ResurrectByCompete();

//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
                }
            }

            nHuntaholicID = HuntaholicManager.Instance.GetHuntaholicID(player.mv);
            if (nHuntaholicID != 0)
            {
                if (HuntaholicManager.Instance.IsHuntaholicDungeon(player.mv))
                {
                    HuntaholicManager.Instance.QuitHunting(nHuntaholicID, player, true, (player.m_nHP == 0) ? 1 : 2);

                    rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                    al = new AutoLock(rl.handle);
                    ServerLog.Log((ushort)0x905,player.GetAccountID(),player.GetSID(),8,0,0,0,(long)player.mv.x, (long)player.mv.y,player.m_layer,0,
                        player.m_nEXP,player.GetAccountName(),player.GetName(),"","");

                    player.AddHP(player.m_nMaxHP - player.m_nHP);
                    Messages.BroadcastHPMPMsg(player, player.m_nMaxHP - player.m_nHP,0,false);
                }
                else
                {
                    rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                    al = new AutoLock(rl.handle);

                    ServerLog.Log((ushort)0x905,player.GetAccountID(),player.GetSID(),8,0,0,0,(long)player.mv.x, (long)player.mv.y,
                        player.m_layer,0,player.m_nEXP,player.GetAccountName(),player.GetName(),"","");

                    posLobby = HuntaholicManager.Instance.GetLobbyPosition(nHuntaholicID);

                    player.PendWarp((int)posLobby.x, (int)posLobby.y, HuntaholicManager.Instance.GetProperLobbyLayer(nHuntaholicID, player.GetLevel()));

                    uint ct = Globals.GetArTime();
                    player.SetMove(player.GetCurrentPosition(ct),0,ct);

                    RappelzServer.Instance.SetObjectPriority(player, SchedulerObject.Priority.Highest);
                    player.AddHP(player.m_nMaxHP - player.m_nHP);
                    Messages.BroadcastHPMPMsg(player, player.m_nMaxHP - player.m_nHP, 0, false);
                }
//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
            }

            rl = RappelzServer.Instance._LockObjectWithVisibleRange(pTarget);
            al = new AutoLock(rl.handle);

            if (player.m_nHP != 0)
            {
//                    ArcadiaAutoLock::_ArcadiaAutoLock(&v56);
                    return;
            }
            ServerLog.Log((ushort)0x905u,player.GetAccountID(),player.GetSID(), (player.m_StatusFlag & Creature.StatusFlags.CompeteDead) != 0 ? 2 : 1,
                0,0,0, (long)player.mv.x, (long)player.mv.y,player.m_layer,0,player.m_nEXP,player.GetAccountName(),player.GetName(),"","");

            int rtown = 0;
            if ((player.m_StatusFlag & Creature.StatusFlags.CompeteDead) == 0)
            {
                if (player.IsInSiegeDungeon())
                    rtown = 3;
            }
            else
            {
                player.m_StatusFlag &= ~Creature.StatusFlags.CompeteDead;
                rtown = 2;
            }
            strReviveHandler = String.Format("revive_in_town( {0} )", rtown);

            LuaVM.Instance.RunString(player,strReviveHandler);

//            ArcadiaAutoLock::_ArcadiaAutoLock(v6);
        }



        private void onGetRegionInfo(TCPConnection socket, GetRegionInfoPacketCS _packet)
        {
            onGetRegionInfoArRegionFunctor fn = new onGetRegionInfoArRegionFunctor();
            fn.obj = socket.Tag.player;

            float nx = (_packet.x / GameContent.g_nRegionSize);
            float ny = (_packet.y / GameContent.g_nRegionSize);

//             v9 = RappelzServer.Instance._Lock((v2 + 12),nx,ny);
//             ArcadiaAutoLock::ArcadiaAutoLock((v2 - 40),v9);

            RappelzServer.Instance.DoEachVisibleRegion((int)nx,(int)ny, fn.obj.m_layer, fn);
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 40));
        }

        private void onDropQuest(TCPConnection socket, DropQuestPacketCS packet)
        {
            Player p = socket.Tag.player;
            if (p == null)
                return;

            ushort r = 5;
            if (p.DropQuest(packet.quest_id))
                r = 0;

            Messages.SendResult(socket, 603, r, 0);
        }

        private void onGetQuestDetails(TCPConnection socket, GetQuestDetailsPacketCS packet)
        {
            Player p = socket.Tag.player;
            if (p == null)
                return;
            p.SetLastContact("npc", 0);
            Messages.SendQuestInformation(p, packet.quest_id, 0);
            p.ShowDialog();
        }

        private void onChangeLocation(TCPConnection socket, ChangeLocationPacketCS packet)
        {
            Player p = socket.Tag.player;
            if (p == null)
                return;
            p.ChangeLocation(packet.x, packet.y, true, true);
        }


        private void onEmotion(TCPConnection socket, EmotionPacketCS packet)
        {
            Player p = socket.Tag.player;
            if (p == null)
                return;

            RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(p);
            AutoLock al = new AutoLock(rl.handle);

            PacketOut pak = new PacketOut(ClientOutPackets.Emotion);
            pak.WriteUInt32(p.m_hHandle);
            pak.WriteInt32(packet.emotion);
            RappelzServer.Instance.Broadcast((uint)(p.mv.x / GameContent.g_nRegionSize),(uint)(p.mv.y / GameContent.g_nRegionSize), p.m_layer, pak);
//            ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 52));
        }

        private void onCharacterList(TCPConnection socket, CharacterListPacketCS packet)
        {
            ConnectionTag tag = socket.Tag;
            if(tag == null)
                return;

            lock(tag)
            {
                DB_CharacterList pa = new DB_CharacterList(socket, tag.nAccountID);
                DatabaseProcess p = GameDBManager.dbProcess;
                GameDBManager.Instance.Push(p, pa);
            }
            ServerLog.Log(110, 0,0,0,0,0,0,0,0,0,0,0,"","", socket.TcpIpAddress,"");
        }


        private void onAccountWithAuth(TCPConnection socket, AccountWithAuthPacketCS packet)
        {
            if(GameRule.IsBlockedAccount(packet.szAccount))
            {
                Globals.Log.Info("Blocked account logged in: " + packet.szAccount);
                return;
            }
            if(GameRule.bRestrictSpecialChar)
            {
/*
                *(_DWORD *)&szAccount[236] = 0;
                *(_DWORD *)&szAccount[232] = "CodePage";
                c = (XCriticalSection *)buf;
                v8 = ENV();
                pOtherConn = XEnvStruct::GetInt(v8, *(const char **)&szAccount[232], *(int *)&szAccount[236]);
                wstrAllowedSpecialChar._Myres = 7;
                std::basic_string<wchar_t_std::char_traits<wchar_t>_std::allocator<wchar_t>>::_Eos(&wstrAllowedSpecialChar, 0);
                v9 = *(const char **)&GameRule::strAllowedSpecialChar._Bx._Buf[0];
                v70 = 0;
                if ( GameRule.strAllowedSpecialChar._Myres < 0x10 )
                    v9 = (const char *)&GameRule::strAllowedSpecialChar._Bx;
                    MultiByteToWideChar(pOtherConn, 0, v9, -1, (LPWSTR)buf, 256);
                    std::basic_string<wchar_t_std::char_traits<wchar_t>_std::allocator<wchar_t>>::assign(
                    &wstrAllowedSpecialChar,
                    (const wchar_t *)buf);
                    MultiByteToWideChar(pOtherConn, 0, lpMultiByteStr, -1, (LPWSTR)buf, 62);
                    v10 = 0;
                    while ( 1 )
                    {
                        v11 = LOWORD(c->baseclass_0.vfptr);
                        if ( !LOWORD(c->baseclass_0.vfptr) )
                        {
                            LABEL_18:
                            v70 = -1;
                            std::basic_string<wchar_t_std::char_traits<wchar_t>_std::allocator<wchar_t>>::_Tidy(
                            &wstrAllowedSpecialChar, 1,0);
                            v2 = v64;
                            goto LABEL_19;
                        }
                        if ( v11 < 0x30u || v11 > 0x39u )
                        {
                            if ( v11 < 0x61u || v11 > 0x7Au )
                            {
                                if ( v11 < 0x41u || v11 > 0x5Au )
                                {
                                    if ( v11 != 64 )
                                    {
                                        pOtherConn = v11;
                                        if ( std::basic_string<wchar_t_std::char_traits<wchar_t>_std::allocator<wchar_t>>::find(
                                             &wstrAllowedSpecialChar, (const wchar_t *)&pOtherConn, 0, 1u) == -1 )
                                            break;
                                    }
                                }
                            }
                        }
                        c = (XCriticalSection *)((char *)c + 2);
                        ++v10;
                        if ( v10 >= 0x3D )
                            goto LABEL_18;
                    }

                    XStringUtil::TrimLeft(szAccount, " \t\r\n");
                    XStringUtil::TrimRight(szAccount, " \t\r\n");
                    TCPConnection conn = StructPlayer.GetConnectionByAccount(packet.szAccount);
                    pOtherConn = (int)v15;
                    if ( v15 && v15->baseclass_0.baseclass_0.vfptr->IsConnected((IConnection *)v15) )
                    {
                        v16 = v15->baseclass_0.baseclass_0.baseclass_4.m_pTag;
                        GameRule::RegisterBlockAccount(szAccount);
                        *(_DWORD *)&szAccount[232] = *((_DWORD *)v16 + 21);
                        StructPlayer::AddToAutoAccountList(*(int *)&szAccount[232]);
                        v17 = FileLogHandler::GetFileLogHandler();
                        v18 = v17->vfptr;
                        *(_DWORD *)&szAccount[228] = szAccount;
                        *(_DWORD *)&szAccount[224] = "Login try with two or more character at once with one account detected: [%s]";
                        *(_DWORD *)&szAccount[220] = "AutoBlockLog";
                        *(_DWORD *)&szAccount[216] = 0;
                        *(_DWORD *)&szAccount[212] = v17;
                        ((void (*)(FileLogHandler *, _DWORD, _DWORD, const char *, ...))v18->LogStringEx)(
                        v17,
                        0,
                        "AutoBlockLog",
                        "Login try with two or more character at once with one account detected: [%s]",
                        __PAIR__(*(unsigned int *)&szAccount[232], szAccount));
                        v19 = *((_DWORD *)v16 + 20);
                        v20 = FileLogHandler::GetFileLogHandler();
                        v21 = v20->vfptr;
                        *(_DWORD *)&szAccount[208] = v16;
                        *(_DWORD *)&szAccount[204] = lpMultiByteStr;
                        *(_DWORD *)&szAccount[200] = "Login try with two or more character at once with one account detected: [%s] [%s]";
                        *(_DWORD *)&szAccount[196] = v20;
                        ((void (*)(FileLogHandler *, const char *, ...))v21->LogString)(
                        v20,
                        "Login try with two or more character at once with one account detected: [%s] [%s]",
                        lpMultiByteStr,
                        __PAIR__(*(unsigned int *)&szAccount[212], (unsigned int)v16),
                        *(_QWORD *)&szAccount[216],
                        *(_QWORD *)&szAccount[224]);
                        *(_DWORD *)&szAccount[236] = v16;
                        *(_DWORD *)&szAccount[232] = lpMultiByteStr;
                        *(_DWORD *)&szAccount[228] = "Login try with two or more character at once with one account detected: [%s] [%s]\n";
                        v22 = XConsole::Inst(0);
                        XConsole::Printf(v22, *(const char **)&szAccount[228]);
                        *(_DWORD *)&szAccount[236] = 0;
                        if ( v19 )
                        {
                        *(_BYTE *)(v19 + 4384) = 1;
                        StructPlayer::Save((StructPlayer *)v19, szAccount[236]);
                        v23 = *(_DWORD *)v19;
                        v39 = 0;
                        v40 = 0;
                        v36 = 10;
                        v37 = 0;
                        v34 = 0;
                        v35 = 0;
                        v41 = 0;
                        v42 = 0;
                        v57 = 0;
                        v58 = 0;
                        v46 = 0;
                        v47 = 0;
                        v55 = (*(int (__thiscall **)(int))(v23 + 92))(v19);
                        v61 = (*(int (__thiscall **)(int))(*(_DWORD *)v19 + 96))(v19);
                        v53 = (*(int (__thiscall **)(int))(*(_DWORD *)v19 + 72))(v19);
                        v44 = (*(int (__thiscall **)(int))(*(_DWORD *)v19 + 64))(v19);
                        v24 = StructPlayer::GetAccountID((StructMonster *)v19);
                        *(_DWORD *)&szAccount[236] = 0;
                        n1 = v24;
                        *(_DWORD *)&szAccount[232] = &unk_5F42BB;
                        *(_DWORD *)&szAccount[228] = 0;
                        *(_DWORD *)&szAccount[224] = &unk_5F42BB;
                        v25 = *(_DWORD *)v19;
                        *(_DWORD *)&szAccount[220] = -1;
                        *(_DWORD *)&szAccount[216] = (*(int (__thiscall **)(int))(v25 + 60))(v19);
                        *(_DWORD *)&szAccount[212] = -1;
                        *(_DWORD *)&szAccount[208] = StructPlayer::GetAccountName((StructPlayer *)v19);
                        *(_DWORD *)&szAccount[204] = &v39;
                        *(_DWORD *)&szAccount[200] = &v36;
                        *(_DWORD *)&szAccount[196] = &v34;
                        *(_DWORD *)&szAccount[192] = &v41;
                        *(_DWORD *)&szAccount[188] = &v57;
                        *(_DWORD *)&szAccount[184] = &v46;
                        *(_DWORD *)&szAccount[180] = &v55;
                        *(_DWORD *)&szAccount[176] = &v61;
                        *(_DWORD *)&szAccount[172] = &v53;
                        *(_DWORD *)&szAccount[168] = &v44;
                        v26 = &n1;
                    }
                    else
                    {
                        v43 = *((_DWORD *)v16 + 21);
                        *(_DWORD *)&szAccount[232] = &unk_5F42BB;
                        *(_DWORD *)&szAccount[228] = 0;
                        *(_DWORD *)&szAccount[224] = &unk_5F42BB;
                        *(_DWORD *)&szAccount[220] = 0;
                        *(_DWORD *)&szAccount[216] = &unk_5F42BB;
                        *(_DWORD *)&szAccount[212] = -1;
                        *(_DWORD *)&szAccount[208] = v16;
                        *(_DWORD *)&szAccount[204] = &n11;
                        *(_DWORD *)&szAccount[200] = &n10;
                        *(_DWORD *)&szAccount[196] = &n9;
                        *(_DWORD *)&szAccount[192] = &n8;
                        *(_DWORD *)&szAccount[188] = &n7;
                        *(_DWORD *)&szAccount[184] = &n6;
                        *(_DWORD *)&szAccount[180] = &n5;
                        *(_DWORD *)&szAccount[176] = &n4;
                        *(_DWORD *)&szAccount[172] = &n3;
                        *(_DWORD *)&szAccount[168] = &n2;
                        n11 = 0i64;
                        n10 = 10i64;
                        n9 = 0i64;
                        n8 = 0i64;
                        n7 = 0i64;
                        n6 = 0i64;
                        n5 = 0i64;
                        n4 = 0i64;
                        n3 = 0i64;
                        n2 = 0i64;
                        v26 = &v43;
                    }
                    LOG::Log11N4S(
                    0xC80u,
                    v26,
                    *(const __int64 **)&szAccount[168],
                    *(const __int64 **)&szAccount[172],
                    *(const __int64 **)&szAccount[176],
                    *(const __int64 **)&szAccount[180],
                    *(const __int64 **)&szAccount[184],
                    *(const __int64 **)&szAccount[188],
                    *(const __int64 **)&szAccount[192],
                    *(const __int64 **)&szAccount[196],
                    *(const __int64 **)&szAccount[200],
                    *(const __int64 **)&szAccount[204],
                    *(const char **)&szAccount[208],
                    *(int *)&szAccount[212],
                    *(const char **)&szAccount[216],
                    *(int *)&szAccount[220],
                    *(const char **)&szAccount[224],
                    *(int *)&szAccount[228],
                    *(const char **)&szAccount[232],
                    *(int *)&szAccount[236]);
                    (*(void (**)(void))(*(_DWORD *)pOtherConn + 8))();
                    v3 = value;
                }
                v27 = FileLogHandler::GetFileLogHandler();
                *(_DWORD *)&szAccount[236] = lpMultiByteStr;
                v28 = v27->vfptr;
                *(_DWORD *)&szAccount[232] = "Restricted character detected in account. [%s]";
                *(_DWORD *)&szAccount[228] = v27;
                ((void (*)(FileLogHandler *, const char *, ...))v28->LogString)(
                v27,
                "Restricted character detected in account. [%s]",
                lpMultiByteStr);
                *(_DWORD *)&szAccount[236] = lpMultiByteStr;
                *(_DWORD *)&szAccount[232] = "Restricted character detected in account. [%s]\n";
                v29 = XConsole::Inst(0);
                XConsole::Printf(v29, *(const char **)&szAccount[232]);
                (*(void (__thiscall **)(unsigned int))(*(_DWORD *)v3 + 8))(v3);
                std::basic_string<wchar_t_std::char_traits<wchar_t>_std::allocator<wchar_t>>::_Tidy(&wstrAllowedSpecialChar, 1, 0);
*/
            }
            else
            {
                if (packet.szAccount.Length >= 60)
                {
                    return;
                }
                uint player_count = Player.GetPlayerCount();
                uint player_max = 200;
                if (player_count < player_max)
                {
                    bool session_null = socket.Session == null;
//                     lock(socket)
//                         session_null = socket.Session == null;

                    if ( session_null )
                    {
                        // See if we already have a client connected with this account
                        bool err = false;
                        lock(hsAuthAccount)
                        {
                            if(hsAuthAccount.ContainsKey(packet.szAccount))
                            {
                                err = true;
                            }
                            else
                            {
                                hsAuthAccount.Add(packet.szAccount, socket);
                            }
                        }

                        if(err)
                        {
                            Messages.SendResult(socket, 2005, 9, 0);
                            return;
                        }
/*
                            s_AuthAccountCS.baseclass_0.vfptr->UnLock((ILock *)&s_AuthAccountCS);
                            pOtherConn = value + 580;
                            _InterlockedExchangeAdd((signed __int32 *)(value + 580), 1u);
*/
                        Messages.SendLoginToAuth(packet.szAccount, packet.one_time_key);
                    }
                    else
                    {
                        Messages.SendResult(socket, 2005, 6, 0);
                    }
                }
                else
                {
                    Messages.SendResult(socket, 2005, 10, 0);
                }
            }
        }

        private void onCheckCharacterName(TCPConnection socket, CheckCharacterNamePacketCS packet)
        {
            ConnectionTag tag = socket.Tag;
            ushort result = 0;

/*
            lock(tag)
            {
                if(tag.szAccountName.Length < 2)
                {
                    result = 6;
                }
                else if (!GameRule.IsValidName(packet.szName) || GameContent.IsBannedWord(packet.szName))
                {
                    result = 19;
                }
            }
*/

            if(result != 0)
            {
                Messages.SendResult(socket, packet.ID, result, 0);
            }
            else
            {
                DB_CheckCharacterName pa = new DB_CheckCharacterName(socket, packet.szName);
                DatabaseProcess p = GameDBManager.dbProcess;
                GameDBManager.Instance.Push(p, pa);
            }
        }

        private void onDialog(TCPConnection socket, DialogPacketCS packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;

            if (!String.IsNullOrEmpty(packet.trigger))
            {
                RLock rl = RappelzServer.Instance._LockWorld();
                AutoLock al = new AutoLock(rl.handle);
                if (!player.IsValidTrigger(packet.trigger))
                {
                    if (!player.IsFixedDialogTrigger(packet.trigger))
                    {
                        Globals.Log.Error("INVALID SCRIPT TRIGGER! [{0}][{1}]", player.GetName(), packet.trigger);
//                         HIDWORD(n9) = v3 + 5696;
                        Interlocked.Add(ref player.m_nInvalidScriptTriggerCount, 1);
//                         if (player.m_nInvalidScriptTriggerCount == 10)
//                         {
//                             v13 = FileLogHandler::GetFileLogHandler();
//                             v14 = (v3->pConnection->baseclass_0.baseclass_0.vfptr->GetPeerAddress)();
//                             v15 = v13->vfptr;
//                             buf[2] = v14;
//                             buf[1] = StructPlayer::GetAccountName(v3);
//                             buf[0] = v3->baseclass_0.baseclass_0.baseclass_0.baseclass_0.vfptr[3].GetHandle(v3);
//                             strTrigger._Myres = 10;
//                             strTrigger._Mysize = "%d Invalid script triggers sent from\t%20s\t%20s\t%20s";
//                             *&strTrigger._Bx._Buf[12] = "InvalidScript";
//                             *&strTrigger._Bx._Buf[4] = v13;
//                             (v15->LogStringEx)(
//                                 v13,
//                                 0,
//                                 "InvalidScript",
//                                 "%d Invalid script triggers sent from\t%20s\t%20s\t%20s",
//                                 10,
//                                 *buf,
//                                 buf[2]);
//                         }
//                        ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
                        return;
                    }
                }

                NPC npc = GameObject.raw_get(player.GetLastContactLong("npc")) as NPC;
                if (npc == null)
                {
                    if (!player.m_bNonNPCDialog)
                    {
//                        ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
                        return;
                    }
                    player.m_bNonNPCDialog = false;
                }
                
                if (player.IsFixedDialogTrigger(packet.trigger) )
                {
                    player.ClearFixedDialogTrigger();
                }
                else
                {
                    if (player.IsSpecialDialogMenu(packet.trigger))
                        player.ClearSpecialDialogMenu();
                    player.ClearDialogMenu();
                }
                int nPrevChaos = player.m_nChaos;
                long nPrevGold = player.m_nGold;

                string szResult = "";
                LuaVM.Instance.RunString(player, packet.trigger, out szResult);
                if(npc != null)
                {
                    ServerLog.Log((ushort)0xA8F, player.GetAccountID(), player.GetSID(), 0, npc.m_BaseInfo.id, nPrevChaos, nPrevGold, player.m_nChaos, player.m_nGold, (long)player.mv.x,
                        (long)player.mv.y, 0, player.GetAccountName(), player.GetName(), "", packet.trigger);
                }
                if (player.HasDialog())
                    player.ShowDialog();

//                ArcadiaAutoLock::_ArcadiaAutoLock(&_lock);
            }
        }


        private void onContact(TCPConnection socket, ContactPacketCS packet)
        {
            Player player = socket.Tag.player;
            if(player == null)
                return;


            if (player.m_hTradeTarget == 0)
            {
                RLock rl = RappelzServer.Instance._LockObjectWithVisibleRange(player);
                AutoLock al = new AutoLock(rl.handle);
                NPC npc = GameObject.raw_get(packet.handle) as NPC;

                if (npc != null)
                {
                    player.SetLastContact("npc", packet.handle);
                    ServerLog.Log((ushort)0xA8E,player.GetAccountID(),player.GetSID(),0,npc.m_BaseInfo.id,player.m_nChaos,player.m_nGold,0,0,(long)player.mv.x,(long)player.mv.y,0,player.GetAccountName(),player.GetName(),"",npc.m_BaseInfo.contact_script);
                    LuaVM.Instance.RunString(player,npc.m_BaseInfo.contact_script);
                }
//                ArcadiaAutoLock::_ArcadiaAutoLock((v2 - 124));
            }
        }


        private void onCreateCharacter(TCPConnection socket, CreateCharacterPacketCS packet)
        {
            ConnectionTag tag = socket.Tag;
            ushort result = 0;

            lock(tag)
            {
                if (tag.szAccountName.Length == 0)
                {
                    result = 6;
                }
                if (GameRule.bDisableCreateCharacter)
                {
                    result = 16;
                }
                if (packet.info.name.Length == 0 || packet.info.name.Length > 18)
                {
                    result = 6;
                }
/*
                if (!GameRule.IsValidName(packet.info.name, 19, 4, 18) || GameContent.IsBannedWord(packet.info.name) )
                {
                    result = 19;
                    goto LABEL_16;
                }
*/

                if(result != 0)
                {
                    Messages.SendResult(socket, 2002, result, 0);
                    return;
                }

//                packet.info.name = GameRule.ReformatName(packet.info.name);

                DB_CreateCharacter pa = new DB_CreateCharacter(socket, packet.info.name, tag.szAccountName, tag.nAccountID, packet.info.race,
                    packet.info.sex,packet.info.skin_color, packet.info.model_id[0],packet.info.model_id[1],packet.info.model_id[2],
                    packet.info.model_id[3], packet.info.model_id[4], packet.info.hair_color_rgb, packet.info.hair_color_index,
                    packet.info.hide_equip_flag, packet.info.texture_id, packet.info.wear_info[2]);
                DatabaseProcess p = GameDBManager.dbProcess;
                GameDBManager.Instance.Push(p, pa);
            }
        }


        private void onDeleteCharacter(TCPConnection socket, DeleteCharacterPacketCS packet)
        {
            ConnectionTag tag = socket.Tag;

            if ( tag != null )
            {
                lock(tag)
                {
                    // see if this is a valid character name, skipping for now :) testing for crap account id as a filler
                    if(tag.nAccountID == 0)
                    {
                        if (GameRule.bUseAutoJail)
                            Player.AddToAutoAccountList(tag.nAccountID);
                        ServerLog.Log(3200,tag.nAccountID,0,0,0,0,0,0,0,0,12,0,packet.szName,"","","");
                        Messages.SendDisconnectDesc(socket, 101);//DISCONNECT_TYPE_ANTI_HACK);
                    }
                    else
                    {
                        if (GameRule.bUseSecurityNoForDeletingCharacter)
                        {
                            tag.strNameToDelete = packet.szName;
                            PacketOut po = new PacketOut((ushort)ClientOutPackets.SecurityNo,11);
                            po.WriteInt32(2);
                            socket.SendTCP(po);
                            return;
                        }
                        else
                        {
                            DB_DeleteCharacter pa = new DB_DeleteCharacter(socket, tag.szAccountName,packet.szName, tag.nAccountID);
                            DatabaseProcess p = GameDBManager.dbProcess;
                            GameDBManager.Instance.Push(p, pa);
                        }
                    }
                }
            }
        }


        /// <summary>
        /// Handles the ClientLoginResult Packet
        /// </summary>
        public void onClientLoginResult(ClientLoginResultPacketAG packet)
        {
            ushort result = 0;
            TCPConnection conn = null;
            bool found = false;

            // Look up the client based on the account name
            if (packet.result != 0)
            {
                result = 6;
            }
            else
            {
                lock (hsAuthAccount)
                {
                    if (hsAuthAccount.ContainsKey(packet.szAccount))
                    {
                        conn = hsAuthAccount[packet.szAccount];
                        hsAuthAccount.Remove(packet.szAccount);
                        found = true;
                    }
                }
                if (!found)
                {
                    result = 6;
                    Globals.Log.Info("AUTH DEBUG : ACCOUNT LOOK UP FAILED [{0}]", packet.szAccount);
                }
                else
                {
                    if (result == 0)
                    {
                        if (conn != null && conn.Tag != null)
                        {
                            if (Player.RegisterAccount(conn, packet.szAccount))
                            {
                                lock (conn.Tag)
                                {
                                    conn.Tag.szAccountName = packet.szAccount;
                                    conn.Tag.nAccountID = packet.nAccountId;
                                    conn.Tag.bAuthByAuthServer = true;
                                    conn.Tag.nPCBangMode = packet.nPCBangUser;
                                    conn.Tag.nEventCode = packet.nEventCode;
                                    conn.Tag.nAge = packet.nAge;
                                    conn.Tag.nContinuousPlayTime = packet.nContinuousPlayTime;
                                    conn.Tag.nContinuousLogoutTime = packet.nContinuousLogoutTime;
                                }
                                //                            if(GameRule.nSecuritySolutionType != 0)
                                //                            {
                                //                                XSecuritySolutionManager.Instance.InitClientSession(v14, v13);
                                //                            }
                            }
                            else
                            {
                                result = 6;
                                Globals.Log.Error("AUTH DEBUG : ACCOUNT REGISTER FAILED [{0}]", packet.szAccount);
                                //const char *szAccount, unsigned int nContinuousPlayTime, const int nCallerIdx
                                Messages.SendLogoutToAuth(packet.szAccount, 0, 1);
                            }
                        }
                        else
                        {
                            result = 6;
                        }
                    }
                }
            }
            Messages.SendAccountResultWithAuth(conn, packet.szAccount, result);
        }

        public void onKickClient(KickClientPacketAG packet)
        {
//            g_ConnectionTagLock.baseclass_0.vfptr->Lock((ILock *)&g_ConnectionTagLock);
            TCPConnection conn = Player.GetConnectionByAccount(packet.szAccount);

            if(conn != null)
            {
                ConnectionTag tag = conn.Tag;
                Player player = tag.player;
                if (player != null)
                {
                    if(player.LogoutTimer != 0)
                    {
                        Globals.Log.Debug("AUTH DEBUG : KICK PLAYER FAILED [{0}/{1}] - Player is in world and waiting logout by logout-timer."
                            ,packet.szAccount,packet.kick_type,"NULL");
                    }
                    else
                    {
                        Globals.Log.Debug("AUTH DEBUG : KICK PLAYER [{0}/{1}] : Player is led to logout by timer", packet.szAccount, packet.kick_type);
                        tag.nContinuousPlayTime = player.GetContinuousPlayTime();
                        tag.nContinuousLogoutTime = player.GetContinuousLogoutTime();
                        uint logout_time = player.CanLogoutNow() ? GameRule.nLogoutTimer : 0;
                        player.LogoutTimer = logout_time + (uint)Environment.TickCount;
                    }
                }
                if(conn.Socket != null && conn.Socket.Connected)
                {
                    PacketOut o = new PacketOut((ushort)ClientOutPackets.DisconnectDesc);
                    o.WriteByte((byte) packet.kick_type);
                    conn.SendTCP(o);

                    conn.Close();

                    Globals.Log.Debug("AUTH DEBUG : KICK PLAYER [%s/%d] : Connection is closed.", packet.szAccount, packet.kick_type);
                }
                else
                {
                    if(player == null)
                    {
                        Globals.Log.Debug("AUTH DEBUG : KICK PLAYER FAILED [%s/%d] : Logout is in process or unknown state.", packet.szAccount, packet.kick_type);
                        if(GameRule.bForceUnregisterAccountOnKickFail)
                            Player.UnRegisterAccount(packet.szAccount);
                    }
                }
            }
            else
            {
                if(Player.IsRegisteredAccount(packet.szAccount))
                {
                    Globals.Log.Debug("AUTH DEBUG : KICK PLAYER FAILED [%s/%d] - Maybe waiting logout by logout-timer.\n", packet.szAccount, packet.kick_type);
                }
                else
                {
                    // send a kick failed message to the auth server

                    Globals.Log.Debug("AUTH DEBUG : KICK PLAYER FAILED [%s/%d] - Unregistered account", packet.szAccount, packet.kick_type);
                    PacketOut o = new PacketOut((ushort)ServerOutPackets.ClientKickFail);
                    o.FillString(packet.szAccount,61);
                    AuthClientNetwork.Instance.SendMessage(o);
                }
            }
//            v30->UnLock((ILock *)&g_ConnectionTagLock);
        }

        private void onReport(TCPConnection socket,ReportPacketCS packet)
        {
            ServerLog.Log(110, 0,0,0,0,0,0,0,0,0,0,0, "","", socket.TcpIpAddress, packet.report);
        }





















    }
}
